【发布时间】:2016-09-22 21:44:29
【问题描述】:
我正在尝试获取特定人的后代列表。以下是我目前所拥有的:
function getDescendants(id, descendants){
children = getChildren(id);
if(children){
for (var child in children) {
if(children.hasOwnProperty(child)){
descendants.push(getDescendants(children[child].id, descendants));
}
}
}
return getPersonById(id);
}
这一直有效,直到它返回初始调用并忘记了 children 数组。
getChildren 返回子对象的数组 getPersonById 返回一个人对象
感谢任何帮助/建议
【问题讨论】:
-
代码不合逻辑,为什么不直接返回
descendants -
@AbdelrhmanMohamed 好吧,想象后代甚至没有传入想象它的全局......如果我们在循环中这样做
for (var child in children) { if(children.hasOwnProperty(child)){ descendants.push(children[child]); getDescendants(children[child].id); } } -
让我明白这一点,你需要记住第一次调用
getChildren时返回的原始数组吗?您是在尝试制作 b-tree 吗? -
@ryan 正确...但我并没有尝试制作 b-tree,只是在创建结果数组(后代)时尝试遍历树
标签: javascript recursion data-structures