Почему моя рекурсивная функция запускается только один раз? - PullRequest
0 голосов
/ 03 марта 2020

Это код, он перебирает объект, ищущий глубоко вложенные дочерние элементы, и должен останавливаться, когда больше нет дочерних элементов, или он превышает 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)

1 Ответ

3 голосов
/ 03 марта 2020

Когда вы вводите этот блок:

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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...