【发布时间】:2016-03-23 12:03:27
【问题描述】:
我需要在树中按 id 查找节点。为此,我将在两个嵌套循环的帮助下下降。但返回未定义。
function searchInTreeById(node, matchingId) {
var res;
if (node.select('id').get() == matchingId) {
res = node.get();
return res
} else {
if (node.exists('childObjects')) {
node.select('childObjects').map(function (cursor, i) {
cursor.select('children').map(function (cursorChild, j) {
if (cursorChild.select('id').get() === matchingId) {
// console.log(cursorChild.get()) //this console.log is execute
res = cursorChild.get();
return res;
} else {
// console.log(cursorChild.get())
searchInTreeById(cursorChild, matchingId)
}
})
})
} else {
res = node;
}
}
return res
}
【问题讨论】:
-
忽略
searchInTreeById的结果看起来很可疑(不确定“猴面包树”是什么,所以不管它是什么都可以) -
@AlexeiLevenkov 如果我设置 res=searchInTreeById(cursorChild, matchingId),然后 func 返回最后访问的节点...
-
旁注:
map通常是错误的搜索方式——很可能还有另一个函数(类似于Array.find)允许在中间停止迭代。
标签: javascript recursion baobab