我查看了 js 文档,并在研究 object.assign() 中提到的文档时 如果源值是对对象的引用,则它仅复制引用值。
在我的下面的代码片段中,一个改变了原始对象,另一个则没有改变
var objA = {
a: 1,
b: {
c: 2,
d: {
e: 3,
},
},
}
var objC = { t: 1 };
//why this works i.e adds a to objEmpty
// var objEmpty = Object.assign({}, { objC }); //this would add a prop to the objEmpty object
//this doesnt work i.e doesnt add a to objEmpty
var objEmpty = Object.assign({}, objC); //this will not
objC.a = 3;
console.log(objC);
console.log(objEmpty);
我通过尝试不同的场景来了解事情到底是如何工作的,我相信这与引用相关,但是如何?
文档中的另一个示例
const obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
obj1.a = 1;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
obj2.a = 2;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
obj2.b.c = 3;
console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}```
why does js behave this way? why the 3 got changed but the other didn't?
Thanks in advance :)
最佳答案
why does js behave this way? why the 3 got changed but the other didn't?
因为Object.assign()
实际上执行浅复制,所以您需要执行深复制
对对象进行深度复制。
方法有很多,最常见和流行的方法是使用 JSON.stringify()
和 JSON.parse()
。
const oldObj = {a: {b: 1}, c: 2};
const newObj = JSON.parse(JSON.stringify(oldObj));
oldObj.a.b = 3; // will not affect the newObj
console.log('oldObj', oldObj);
console.log('newObj', newObj);
注意:有一个新的 JS 标准,名为 structured cloning
。它适用于所有浏览器:
method creates a deep clone of a given value using the structured clone algorithm.
const clone = structuredClone(object);
关于javascript - 在 js 中复制对象(需要文档中的引用传递指导),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73283123/