题目:
let tree = [ { mc: "chen", children: [ { mc: "chen1", children: [ { mc: "chen1-1", children:[ { mc: "chen1-1-1", children:[ {mc: "chen1-1-1-1"}, {mc: "chen1-1-1-2"} ]
},
{ mc: "chen1-1-2"},
]
},
{
mc: "chen1-2",
},
{
mc: "chen1-3",
},
],
},
{
mc: "chen2",
},
{
mc: "chen3",
},
{
mc: "chen4",
children: [
{
mc: "chen4-1",
},
{
mc: "chen4-2",
},
{
mc: "chen4-3",
},
],
},
],
},
];
方法1:(正确)
let result
function findMC(list,mc){
for(let i=0;i<list.length;i++){
if(list[i].mc===mc){
result = list[i].mc
break
}
if(list[i].children && list[i].children.length>0){
findMC(list[i].children,mc)
}
}
return result
}
console.log(findMC(tree,'chen1-1-1-1'))
前提是result要放到外面
but!!!
如果result放到了里面如:
结果为:
但是换成一个层级比较深的:
结果为undefined
所以这个方法并不严谨 因为不论递归有没有找到,都会修改result的值
修改:::
加一层判断(保证递归找到了值才能返回)
继续优化(省一个变量,性能优化些)
function findMC(list,mc){
for(let i =0;i<list.length;i++){
if(list[i].mc===mc){
return list[i].mc
break
}
if(list[i].children && list[i].children.length > 0){
let re = findMC(list[i].children,mc)
if(re) return re
}
}
}
console.log(findMC(tree,'chen1-1-1-1'))
关于此题目的深层原因还是需要不断揣摩,道行还是太浅,哭唧唧~~~