[英]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.