const getSelectedChildFacets = function (parent) { parent?.childrens?.forEach((child) => { if (child.selected && !child.partiallySelected) { // 如果是全选 if (parentValues.includes(child.value)) { // 如果是父节点,非子节点则继续向下查找 getSelectedChildFacets(child); } else { // 如果是子节点,则存起来 arrSelectedFacets.push(child.value); } } else if (child.selected && child.partiallySelected) { // 如果是半选,则继续向下查找 getSelectedChildFacets(child); } }); };
arrFacetValues.forEach((parent) => { if (parent.selected && !parent.partiallySelected) { // 全选 if (parentValues.includes(parent.value)) { // 全选且是父节点,向下查找 getSelectedChildFacets(parent); } else { // 子节点则存到树组中 arrSelectedFacets.push(parent.value); } } if (parent.selected && parent.partiallySelected) { // 如果是半选,继续向下查找 getSelectedChildFacets(parent); } });
如何将两个方法合并成一个方法
如图parentValues = ['BC', 'BC-SRV', 'BC-SRV-COM'],
想得到的是选中的树组arrSelectedFacets = ['BC-SRV-COM-FTP', 'BC-SRV-COM-TEL']
const arrFacetValues = [ { value: "BC", selected: true, partiallySelected: true, childrens: [ { value: "BC-SRV", selected: true, partiallySelected: true, childrens: [ { value: "BC-SRV-COM", selected: true, partiallySelected: true, childrens: [ { value: "BC-SRV-COM-FTP", selected: true, partiallySelected: false, childrens: [], }, { value: "BC-SRV-COM-TEL", selected: true, partiallySelected: false, childrens: [], }, ], } ], } ], } ]
如果 BC-SRV-COM 下的子节点都选中,则arrSelectedFacets=['BC-SRV-COM']
const getSelectedChildFacets = function (node, parentValues, arrSelectedFacets) { if (node.selected) { if (!node.partiallySelected && !parentValues.includes(node.id)) { arrSelectedFacets.push(node.id); } else { node.childrens.forEach((child) => { getSelectedChildFacets(child, parentValues, arrSelectedFacets); }); } }};const parentValues = ['BC', 'BC-SRV', 'BC-SRV-COM'];const arrSelectedFacets = [];const arrFacetValues = [ { id: "BC", selected: true, partiallySelected: true, childrens: [ { id: "BC-SRV", selected: true, partiallySelected: true, childrens: [ { id: "BC-SRV-COM", selected: true, partiallySelected: true, childrens: [ { id: "BC-SRV-COM-FTP", selected: true, partiallySelected: false, childrens: [], }, { id: "BC-SRV-COM-TEL", selected: true, partiallySelected: false, childrens: [], }, ], } ], } ], }];arrFacetValues.forEach((parent) => { getSelectedChildFacets(parent, parentValues, arrSelectedFacets);});console.log(arrSelectedFacets); // ['BC-SRV-COM-FTP', 'BC-SRV-COM-TEL']
如何在PHP Smarty中优化这段代码? 现在我有一个代码让我困惑,有一个简单的代码。 当我搜索需要推送值的代码时。 优化如何发挥作用?我能写到数组吗?如果它可以写入数组,我该怎么办?
这种地图效果是叫什么?具体该使用哪种技术实现,如何实现,有具体的示例吗?
我认为代码(如下)已经优化(只需使用比相同逻辑的初始版本更少的变量) > 在优化过程中,我应该考虑哪些因素? 这是代码(也在jsfiddle上) 这是代码的解释。“处理”函数在数组中查找相同的值,对于每个相同的值,它通过将一个数字挂起到该值来更改值,“数字”表示它在数组中找到的值的计数。 例如arr=["x","x","y","z"]将返回["x(1)","x(2)","y","z"]"y"和"z