正确的:
handelMultiSelectResFactorial(nodes) {
for (let i = 0, length = nodes.length; i < length; i++) {
if (nodes[i]?.children?.length) {
return this.handelMultiSelectResFactorial(nodes[i].children);
}
return nodes[i];
}
},
一个可以终止的for循环
for (let i = 0; ; i++) {
nodeIds.push(res[i].ID);
if (i === this.maxCheckNum - 1) {
break;
}
}
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
并没有按照想要结果进行退出,错误的demo:
let res = [
{
ID: 'site_1',
children: [
{
ID: 'area_1',
children: [
{
ID: 'shop_9',
},
],
},
{ ID: 'shop_1' },
{ ID: 'shop_2' },
{ ID: 'shop_3' },
],
},
]
function handleRes(nodes) {
for (let i = 0, length = nodes.length; i < length; i++) {
if (nodes[i]?.children?.length) {
console.log(nodes[i].children)
handleRes(nodes[i].children) //导致了闭包,然后就不会正常的按照预料的去执行
} else {
return nodes[i]
}
}
}
let a = handleRes(res)
console.log('结果', a)
// 其实是会退出的
for (let index = 0; index < 6; index++) {
console.log(index)
if (index > 3) {
return
}
}
handelMultiSelectResFactorial(nodes) {
for (let i = 0, length = nodes.length; i < length; i++) {
if (nodes[i]?.children?.length) {
this.handelMultiSelectResFactorial(nodes[i].children); // 闭包
}else {
return nodes[i]; // 甚至还加了break,还是无法退出
}
}
},