提问人:mert 提问时间:8/9/2022 最后编辑:Pointymert 更新时间:8/9/2022 访问量:339
当有嵌套对象时,如何将真实对象的嵌套对象分配给其他变量,这会影响真实对象吗?
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?
问:
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);
答: 暂无答案
评论
let newUser = user;
不制作浅拷贝。在该声明之后,两个变量将引用同一个(单个)对象。newUser = Object.assign( {}, user.address )