我有以下递归功能,但它不起作用...... 它的搜索范围远远超过了firstPageChild'然后完成。谁能发现这里有什么问题? 我确信它的东西很简单,但此刻它让我很难过。
var pageMap = [{"pageID" : "mainPage",
"children": [{"pageID" : "firstPage",
"children": [{"pageID" : "firstPageChild",
"children": []
}]
},
{"pageID" : "secondPage",
"children": [{"pageID" : "secondPageChild1",
"children": []
}, {"pageID" : "secondPageChild2",
"children": []
}]
},
{"pageID" : "thirdPage",
"children": [{"pageID" : "thirdPageChild1",
"children": []
}, {"pageID" : "thirdPageChild2",
"children": []
}]
}]
}];
function findObjectById(root, id) {
debugger;
var k, pageVar;
if (root.children) {
for (k in root.children) {
pageVar = root.children[k];
if (pageVar.pageID == id) {
return pageVar;
}
else if (pageVar.children.length) {
return findObjectById(pageVar, id);
}
}
}
};
for (var i = 0, len = pageMap.length; i < len; i++) {
var myObj = findObjectById(pageMap[i], "secondPageChild2");
}
console.log(myObj);
答案 0 :(得分:1)
替换
上的return findObjectById(pageVar, id);
pageSrch = findObjectById(pageVar, id);
if(pageSrch){
return pageSrch;
}