递归函数,适用于第一次调用但不适用于第二次调用

时间:2017-03-25 22:02:42

标签: javascript node.js recursion

尝试在node.js中创建递归函数,第一次调用有效但第二次调用失败。

为了更容易向我展示失败的地方,我举了一个例子,我用一个对象数组替换数据库,并在其中搜索函数findElements。

let data = [
  {id: 1, value: "1st", articleId: 1, lvl: 0, sons: [3, 7], positif: 3, negatif: 2},
  {id: 2, value: "2nd", articleId: 2, lvl: 0, sons: [], positif: 5, negatif: 8},
  {id: 3, value: "3rd", articleId: 1, lvl: 1, sons: [5, 6, 8], positif: 9, negatif: 4},
  {id: 4, value: "4th", articleId: 1, lvl: 0, sons: [], positif: 3, negatif: 52},
  {id: 5, value: "5th", articleId: 1, lvl: 2, sons: [], positif: 8, negatif: 2},
  {id: 6, value: "6th", articleId: 1, lvl: 2, sons: [9], positif: 3, negatif: 1},
  {id: 7, value: "7th", articleId: 1, lvl: 1, sons: [], positif: 5, negatif: 0},
  {id: 8, value: "8th", articleId: 1, lvl: 2, sons: [], positif: 3, negatif: 0},
  {id: 9, value: "9th", articleId: 1, lvl: 3, sons: [], positif: 123, negatif: 102}
]

function findElements(object, elementName, value) {
  let res = []
  object.forEach((element) => {
    if(element[elementName] == value){
      res.push(element)
    }
  })
  return res
}

function recursiveFindSons(element) {
  for (let i = 0; i < element.length; i++) {
    for (let j = 0; j < element[i].sons.length; j++) {
      console.log(element[i].sons[j])
      element[i].sons[j] = findElements(data, 'id', element[i].sons[j])[0]
      if(element[i].sons[j].sons.length>0)
      {
        element[i].sons[j] = recursiveFindSons([element[i].sons[j]])
      }
    }
  }
  return element
}

app.get('/', function(req, res) {
  let result = recursiveFindSons(findElements(data, 'lvl', 0))
  let json = JSON.stringify({result}, null, 2)
  res.status(200).send(json)
})

console.log(element[i].sons[j])显示问题: 记录第一个电话:

3
5
6
9
8
7

记录第二个电话:

[ { id: 3,
value: '3rd',
articleId: 1,
lvl: 1,
sons: [ [Object], [Object], [Object] ],
positif: 9,
negatif: 4 } ]

我知道有些东西可以保留记忆中第一个电话的结果,但我不知道如何避免这种情况,我不明白为什么......任何人都可以帮助并解释我?

使用SciFiThief解决方案进行编辑

function recursiveFindSons(elements, result) {

  function copyElement(element) {
    return {id: element.id, value: element.value, articleId: element.articleId, lvl: element.lvl, sons: [], positif: element.positif, negatif: element.negatif}
  }

  if(!result) {
    result = []
    for(var i=0; i<elements.length; i++) {
      result.push(copyElement(elements[i]))
    }
  }

  for (let i = 0; i < elements.length; i++) {
    for (let j = 0; j < elements[i].sons.length; j++) {
      let elById = findElements(data, 'id', elements[i].sons[j])[0]
      result[i].sons.push(copyElement(elById))
      console.log(result)
      if(elById.sons.length>0)
      {
        result[i].sons[j] = recursiveFindSons([elById], result[i].sons[j][0])[0]
      }
    }
  }
  return result
}

1 个答案:

答案 0 :(得分:0)

您可以使用node-inspector https://www.npmjs.com/package/node-inspector来调试您的应用程序,遍历您的每一行功能。你很快就会发现它有什么问题。

function recursiveFindSons(element) {
  for (let i = 0; i < element.length; i++) {
    for (let j = 0; j < element[i].sons.length; j++) {
      // 1. The next line is mutating the data you go through
      element[i].sons[j] = findElements(data, 'id', element[i].sons[j])[0]
      if(element[i].sons[j].sons.length > 0) {
         element[i].sons[j] = recursiveFindSons([element[i].sons[j]]);
      }
    }
  }
  return element;
}

首先,改变您经历的数据以找到您感兴趣的内容是一件坏事。

element[i].sons[j] = ... // this is mutating of source data. 
                         // You should not do this, 
                         // it makes function's behavior unpredictable. 
                         // It's like iterating through array and deleting
                         // elements from it on each iteration. 

它将取代&#34; sons&#34;中的id。数组中的对象条目数组。 同样如下:

 element[i].sons[j] = recursiveFindSons([element[i].sons[j]]);

我假设您想要提供您提供的第一个日志的输出。要做到这一点,你可以这样做:

function recursiveFindSons(elements, result) {
  result = result || []; // define result array on first call or use it from args.
                         // There's no original data mutations, only local result variable

  for (let i = 0; i < elements.length; i++) {
    for (let j = 0; j < elements[i].sons.length; j++) {
      let son = elements[i].sons[j];
      result.push(son);
      let elById = findElements(data, 'id', son)[0];
      if(elById.sons.length > 0) {
         recursiveFindSons([elById], result); // pass result array to the next function call
      }
    }
  }
  return result;
}

JSFiddle:https://jsfiddle.net/fwbumpx9/

相关问题