【问题标题】:Why is my recursive function seems to run only once?为什么我的递归函数似乎只运行一次?
【发布时间】: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


【解决方案1】:

当你进入这个区块时:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多