2017-02-17 60 views
1

我不知道我在做什么错,但这段代码第一次执行前后发生了改变recipesData对象,并在第二次执行我得到非常大的变量(因为代码使用recipesData )。的Node.js以某种方式改变了我的递归函数对象

如果我使用调试器对象(recipesData)开始变化的位置:

child[child_part] *= craft[part]; 

child甚至不相关的recipesData另一个变量。

这是我使用的代码:在JavaScript

first ex. second execute. 
282  11340 
336  69498 
390  108918 
82  3400 
82  3397 
27  745 
270  10629090 
27  19683 

// Some object with date 
var recipesData = { 
    'test1': { 
     'example1': 544, 
     'example2': 323 
    }, 
    'test2': { 
     'example1': 123 
    }, 
} 

// Function that I call from main file 
module.exports.getFinished = function (item, stock) { 
    // Create temp 'recipes' variable 
    var recipes = recipesData[item]; 
    // Execute recursive func 
    var basics = getBasics(recipes); 

    return basics; 
}; 

// Create 'finished' empty object 
var finished = {}; 

// My recursive fuction that works pretty nice at first 
function getBasics(craft) { 
    for (var part in craft) { 
     for (var recipe in recipesData) { 
      if (recipesData.hasOwnProperty(part)) { 
       var child = recipesData[part]; 
       break; 
      } else 
       child = null; 
     } 

     if (child) { 
      for (var child_part in child) 
       // HERE it's CHANGE my 'recipesData' object at the top! 
       child[child_part] *= craft[part]; 
      getBasics(child); 
     } else { 
      if (finished.hasOwnProperty(part)) 
       finished[part] += craft[part]; 
      else 
       finished[part] = craft[part]; 
     } 
    } 
    return finished; 
} 

回答

0

对象由参考,不值传递。在getBasics内部,craft是与recipeData相同的基础数据的参考。 child是参考recipeData的内部对象之一。

因此,当您使用*=child中的属性指定新值时,它将使用recipeData变量引用的相同数据进行操作。

+0

感谢答案,我理解的主要思想,但是还是不知道如何解决它,而不喜欢做真正的副本解决方法... –

0

以下的孩子只是参考recipesData。

if (recipesData.hasOwnProperty(part)) { 
      var child = recipesData[part]; 
      break; 
     } else 
      child = null; 
    } 

因此稍后修改实际recipesData。如果你想有真正的数组副本,你可以做例如用切片()或CONCAT(),如:

child = [].concat(recipesData[part]);