JavaScript - 递归函数中的错误是什么?

时间:2018-03-26 07:34:22

标签: javascript

我尝试获取查询ID的完整路径。例如,getPath(6,rawData)应返回[1,2,6]。但是,它返回[6,6,6]。当我在代码中尝试console.log时,看起来自调用函数内的节点的值将覆盖外部节点的值。我无法弄清楚递归函数有什么问题。或者有人可以教我一种实现同一目标的新方法?

以下是代码:

const getPath = (id, list) => {
  if (!list || !Array.isArray(list)) {
    return false
  }

  for (node of list) {
    if (node.id === id) {
      return [node.id]
    }

    let res = getPath(id, node.children)

    if (res) {
      return [node.id, ...res]
    }
  }

  return false
}

const rawData = [{
    id: 1,
    parent: null,
    children: [{
      id: 2,
      parent: 1,
      children: [{
        id: 4,
        parent: 2,
        children: null
      }, {
        id: 5,
        parent: 2,
        children: null
      }, {
        id: 6,
        parent: 2,
        children: null
      }]
    }]
  },
  {
    id: 3,
    parent: null,
    children: [{
        id: 7,
        parent: 3,
        children: [{
          id: 9,
          parent: 7,
        }]
      },
      {
        id: 8,
        parent: 3,
      }
    ]
  }
]

console.log(getPath(2, rawData))

1 个答案:

答案 0 :(得分:5)

您需要声明变量node,因此它是函数的本地变量。

const getPath = (id, list) => {
  if (!list || !Array.isArray(list)) {
    return false
  }

  for (let node of list) {
    if (node.id === id) {
      return [node.id]
    }

    let res = getPath(id, node.children)

    if (res) {
      return [node.id, ...res]
    }
  }

  return false
}

const rawData = [{
    id: 1,
    parent: null,
    children: [{
      id: 2,
      parent: 1,
      children: [{
        id: 4,
        parent: 2,
        children: null
      }, {
        id: 5,
        parent: 2,
        children: null
      }, {
        id: 6,
        parent: 2,
        children: null
      }]
    }]
  },
  {
    id: 3,
    parent: null,
    children: [{
        id: 7,
        parent: 3,
        children: [{
          id: 9,
          parent: 7,
        }]
      },
      {
        id: 8,
        parent: 3,
      }
    ]
  }
]

console.log(getPath(2, rawData))