我不知道我在做什么错,但这段代码第一次执行前后发生了改变我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;
}
感谢答案,我理解的主要思想,但是还是不知道如何解决它,而不喜欢做真正的副本解决方法... –