gpt4 book ai didi

javascript - 为什么在动态填充对象时所有对象属性值都在变化? Javascript

转载 作者:行者123 更新时间:2023-11-30 20:21:01 25 4
gpt4 key购买 nike

注意: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"}
}
}

经过更多调试后,我发现对象正在更改其值(它在代码中用“警告”注释)。是在所有对象值都改变的那一行

最佳答案

除非您使用某种深度复制,否则您只是复制对原始对象的引用。参见 What is the most efficient way to deep clone an object in JavaScript?

关于javascript - 为什么在动态填充对象时所有对象属性值都在变化? Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51451226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com