[英]Why code after return statement executing inside for-in loop in javascript?
我的变量看起来像这样
var widgets2 = [{
id: "1",
title: 'title',
children: [],
},
{
id: "2",
title: 'title2',
children: []
},
{
id: "3",
title: 'title3',
children: [{
id: "4",
title: 'title4',
children: [],
}, {
id: "5",
title: 'title5',
children: [],
children: [{
id: "6",
title: 'title6',
children: [],
},
{
id: "7",
title: 'title7',
children: [],
}
]
}],
},
{
id: "9",
title: 'title9',
children: [],
}
]
function 代码如下所示
function findTheKey(id,widget){
let newObj=[...widget];
for(var key in newObj){
if(newObj[key]['id']==id){
console.log(newObj[key])
return newObj[key];
}
console.log("came here")
if(newObj[key].hasOwnProperty("children")){
findTheKey(id,newObj[key].children);
}
}
}
当使用以下代码调用 function
var result=findTheKey(4,widgets2);
console.log(result)
结果看起来像这样
{id: "4", title: "title4", children: Array(0)}
came here
这意味着即使在执行 return 语句、执行 console.log 之后,任何帮助都将受到高度赞赏。 谢谢
由于这是一个递归的function,所以返回并没有你期望的效果,你需要一个递归的function之外的变量来保持你想要找到的当前Z9ED39E2EA931586B6A985A6942EF573E
例如,请参见下面的代码段:
var widgets2 = [ { id: "1", title: "title", children: [], }, { id: "2", title: "title2", children: [], }, { id: "3", title: "title3", children: [ { id: "4", title: "title4", children: [], }, { id: "5", title: "title5", children: [], children: [ { id: "6", title: "title6", children: [], }, { id: "7", title: "title7", children: [], }, ], }, ], }, { id: "9", title: "title9", children: [], }, ]; let found; function findTheKey(id, widget) { let newObj = [...widget]; for (var key in newObj) { if (newObj[key]["id"] == id) { found = newObj[key]; break; } if (newObj[key].hasOwnProperty("children")) { findTheKey(id, newObj[key].children); } } return found; } var result = findTheKey(4, widgets2); console.log(result);
您应该为此更新您的问题,但由于您在评论中要求,这就是我的建议。
function findTheKey(id, widget) {
const newObj = [...widget];
for (const key in newObj) {
if (newObj[key]["id"] === `${id}`) {
return newObj[key];
}
if (newObj[key].hasOwnProperty('children')) {
/* Use the result of the recursive function */
const foundObject = findTheKey(id, newObj[key].children);
if(foundObject) return foundObject;
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.