【发布时间】:2017-02-17 22:29:35
【问题描述】:
我不知道我做错了什么,但是在第一次执行后这段代码改变了我的recipesData对象,在第二次执行时我得到了非常大的变量(因为代码使用recipesData) .
如果我使用调试器对象(recipesData)从这里开始改变:
child[child_part] *= craft[part];
child 甚至是另一个与recipesData 无关的变量。
这是我使用的代码:
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;
}
【问题讨论】:
标签: javascript node.js object recursion scope