JS中的递归函数

Recursive function in JS

我在递归函数中遇到了一个非常奇怪的问题。 我的代码如下:

tree_generator(startNode, dictionary) {
      let resultNode = startNode
      // find node name from dictionary
      let hasChild = dictionary[resultNode.name]
        ? dictionary[resultNode.name].parts.length > 0
          ? true
          : false
        : false
      if (hasChild) {
        //create child node object
        let children = _.map(dictionary[resultNode.name].parts, item => {
          let childpart = {
            id: 'd_' + item.name,
            name: item.name,
            children: [],
            ontology_name: item.partIri.replace(/.*otl\//, '') // need to update to related uri value
          }
          this.level = this.level + 1
          // recurve to get the result for child node
          this.tree_generator(childpart, dictionary)
          return childpart
        })
        console.log('real child')
        console.log(children)
        resultNode.children = children
        console.log('real result node in tree')
        console.log(resultNode)
      } else {
        //it is a leaf, delete child node
        delete resultNode.children
      }
      return resultNode
    }

当我传递不同的字典参数时,return结果应该不同,但实际上,它总是return与最后一个字典值相同的结果。

当我控制台记录 childrenresultNode value, children value 永远是正确的字典,但是 resultNode 总是分配一个与真正的 children 不同的值。

有谁知道我做错了什么吗?

测试数据组: 第一组: 起始节点:

{
      id: '0_d_TestOne',

      name: 'TestOne',

      children: [],

      ontology_name: 'testOne'
    }

词典:

{
      TestOne: { uri: 'TestOne', parts: [{ name: 'testTwee', partIri: 'http://otl/testTee' }] },
      testTwee: { uri: 'testTwee', parts: [{ name: 'testDrie', partIri: 'http://otl/testDrie' }] },
      testDrie: { uri: 'testDrie', parts: [{ name: 'testVier', partIri: 'http://otl/testVier' }] },
      testVier: { uri: 'testVier', parts: [{ name: 'TestVijf', partIri: 'http://otl/TestVijf' }] }
    }

第 2 组: 起始节点:

{
      id: '0_d_TestOne',

      name: 'TestOne',

      children: [],

      ontology_name: 'testOne'
    }

词典:

{
      TestOne: { uri: 'TestOne', parts: [{ name: 'TestTwo', partIri: 'http://otl/TestTwo' }] },
      TestTwo: { uri: 'TestTwo', parts: [{ name: 'TestThree', partIri: 'http://otl/TestThree' }] },
      TestThree: {
        uri: 'TestThree',
        parts: [{ name: 'TestFour', partIri: 'http://otl/TestFour' }]
      },
      TestFour: { uri: 'TestFour', parts: [{ name: 'TestFive', partIri: 'http://otl/TestFive' }] }
    }

起始节点相同,字典不同,期望的树输出应该不同

the start node is the same, the expected tree output should be different

这是你的问题:你的函数不会创建新的输出,它会修改你传入的startNode。如果你传入相同对象两次使用不同的字典,只有最后一次调用的结果将存储在您的对象中。

我建议不要传入对象,只传入要从字典中获取的树节点的名称,并且总是创建一个新的结果对象。