【发布时间】:2020-03-03 18:15:53
【问题描述】:
这是代码,它会遍历一个对象以寻找深度嵌套的孩子,并且一旦没有更多孩子或超过 ALLOWED_NESTING_DEPTH 就应该停止。
console.log 似乎只运行一次,虽然我得到了正确的数字。
const ALLOWED_NESTING_DEPTH = 4
function traverseChildren (childrenIdList, parentsNesting = 0) {
parentsNesting++
if (parentsNesting > ALLOWED_NESTING_DEPTH || _.isEmpty(childrenIdList)) {
console.log(parentsNesting) // Why does this show only once even if there are many levels of nesting?
return parentsNesting
}
let children = childrenIdList.map(child => _.find(tree.items, { id: child }))
let allChildren = []
if (!_.isEmpty(children)) {
allChildren = _.flattenDeep(children.map(child => child.children))
}
return traverseChildren(allChildren, parentsNesting)
}
traverseChildren(someChild)
【问题讨论】:
-
childrenIdList只为空一次? if 的每个条件的简单控制台日志会告诉您为什么它是错误的。或者把debugger;扔进去看看 -
因为您只在基本情况下执行
console.log,而不是在每个函数调用中? -
我猜这与
flattenDeep有关 -
什么是
someChild?你能把它扩展成minimal reproducible example吗? -
仅供参考:严格来说,这只是尾递归。因为
traverseChildren调用traverseChildren的唯一位置是函数的最后。这意味着你可以把它写成一个循环。通过将整个内容封闭在while(true)块中,然后将childrenIdList = allChildren而不是调用traverseChildren来做到这一点。
标签: javascript arrays object recursion