这是代码,它会遍历一个对象,寻找深度嵌套的子对象,并在没有更多子对象或超过 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)
最佳答案
当您进入此 block 时:
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
}
...您正在返回一个对象并且不再调用该函数。换句话说,这是您的终止案例。您只经过这里一次,因此您只会看到一个 console.log
。
关于javascript - 为什么我的递归函数似乎只运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60513303/