javascript - 为什么在动态填充对象时所有对象属性的值都在变化?Javascript
问题描述
注意:subObj, subObj2, subObj3, subObj4 都是对象{}
这是代码:
for (var key in subObj) {
if (subObj.hasOwnProperty(key)) {
subObj2 = subObj[key];
subObj3["player"] = subObj2["player"];
subObj3["bodypart"] = subObj2["bodypart"];
subObj3["type"] = subObj2["type"];
subObj3["result"] = subObj2["result"];
aux = subObj2["zone"];
//WARNING: here is the problem. All object content (except keys) are being set to subObj3
console.log(subObj4);
//initialize > important! (this creates new properties in object)
if (!subObj4.hasOwnProperty(aux)) {
subObj4[aux] = {};
}
if (!subObj4[aux].hasOwnProperty(key)) {
subObj4[aux][key] = {};
}
//store
subObj4[aux][key] = subObj3;
console.log("aux = ", aux, " key = ", key);
console.log(subObj3);
console.log(subObj4);
} //endif
} //endfor
控制台日志
电流输出:
第一个循环:
//log of "aux" and "key"
aux = e3c , key = 1
//log of "subObj3"
{player: "john", bodypart: "h", type: "open_t", result: "correct"}
//log of "subObj4"
{e3c:{
1:{player: "john", bodypart: "h", type: "open_t", result: "correct"}
}
}
第二个循环:
//log of "aux" and "key"
aux = e3c , key = 4
//log of "subObj3"
{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
//log of "subObj4"
{e3c:{
1:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
4:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
}
}
预期输出:
//log of "subObj4"
{e3c:{
1:{player: "john", bodypart: "h", type: "open_t", result: "correct"}
4:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
}
}
经过更多调试后,我发现对象正在更改其值(它在代码中用“警告”注释)。在那一行中,所有对象值都发生了变化
解决方案
除非您使用某种深拷贝,否则您只是在复制对原始对象的引用。请参阅在 JavaScript 中深度克隆对象的最有效方法是什么?
推荐阅读
- latex - (页)MS Word 文档 - 在 LaTeX 而不是 MathML 中导出方程?
- node.js - 在移动浏览器上对 toastify return 的错误做出反应
- node.js - 使用 papaparse 忽略 csv 文件的标题
- sql - 在同一个表中分组和连接行 - SQLite
- python - 在我将其更改为“agg”之前,我的后端是什么?
- python - 为什么我的 tkinter 标签会出现“未知选项“-Text””?
- python - 两个 Asyncio 同时休眠
- assembly - 如何比较输入数字和汇编中的数字?
- batch-file - 如何仅移动与另一个文件夹中的文件名匹配的文件
- c - 如何在 C 中定义一个接受格式化输入字符串的函数?