我不知道我做错了什么,但是第一次执行后这段代码更改了我的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 中的对象是通过引用传递的,而不是通过值传递的。在 getBasics
内部,craft
是对与 recipeData
相同的底层数据的引用。 child
是对 recipeData
内部对象之一的引用。
因此,当您使用 *=
为 child
中的属性分配新值时,它对 recipeData
变量引用的相同数据进行操作。
关于javascript - Node.js 用递归函数以某种方式改变了我的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308469/