当 break 语句用于循环语句时,会终止执行循环,并执行循环后代码(如果有的话)
let arr = [{
name: '3',
children: [{
name: '3-1',
children: [{
name: '3-1-1',
children: [{
name: '3-1-1-1'
}]
}]
}]
}]
function getLayer(list, name, layer) {
let res = layer;
for (let i = 0; i < list.length; i++) {
if (list[i].name === name) {
break;
} else {
if (list[i].children) {
res = getLayer(list[i].children, name, layer + 1)
}
}
}
return res;
}
console.log(getLayer(arr, '3-1-1', 1), '=====> 3')
网友评论