当有嵌套对象时,如何将真实对象的嵌套对象分配给其他变量,这会影响真实对象吗?

When there is a nested object, how can I assign a nested object of the real object to other variable and Is this affect the real object?

提问人:mert 提问时间:8/9/2022 最后编辑:Pointymert 更新时间:8/9/2022 访问量:339

问:

let user = {
    name: "John",
    age: 30,
    address: {
        country: "England",
        city: "Manchester"
    }
}

let newUser = user; // shallow copy

newUser = newUser.address; // I assigned the nested object to newUser variable. (what happened in this place? Did I create a new object in memory? but if I make this(newUser = {country:"testing", city: "xxx"}), it will create a new object in memory. What is the differences between them?)

newUser.city = "London" // I change city of newUser, but this affects User object. Why And How affect User object?

console.log("newUser", newUser);
console.log("user", user);  
JavaScript的 JSON的 打字稿 不变性 可变

评论

2赞 Pointy 8/9/2022
let newUser = user;制作浅拷贝。在该声明之后,两个变量将引用同一个(单个)对象。
1赞 Deepak Kamat 8/9/2022
newUser = Object.assign( {}, user.address )
0赞 Xyndra 8/9/2022
这可能会有所帮助: stackoverflow.com/questions/12690107/...

答: 暂无答案