javascript - 为什么我的递归函数似乎只运行一次?

标签 javascript arrays object recursion

这是代码,它会遍历一个对象,寻找深度嵌套的子对象,并在没有更多子对象或超过 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/

相关文章:

php - 使用 JQuery 解析嵌套 JSON

python - 加密安全伪随机洗牌 python 中的列表或数组

c++ - C++ 中对象/类的动态数组

php - 解析我无法识别为对象、数组或 Json 的字符串

javascript - 我可以在不分配变量的情况下返回 else/if 语句的答案吗?

javascript - 在 JavaScript 中访问 iframe 元素

javascript - div 之间不需要的水平边距

javascript - 当对象在多个其他对象中时,console.log 返回 [Object]

Javascript:隐藏/使客户端对象难以理解

c++ - 如何初始化一个大小最初未知的数组?