现在你的代码很清楚了!让我们来看看
var chat = {
users: [
{
username: "test"
},
{
username: "test1"
}
]
},
// creating reference from save to chat.users
save = chat.users,
i = 0;
if (chat.users[i + 1]) {
// should be chat.users[1].username ("test1")
console.log("1: " + chat.users[i + 1].username); // output "test1"
}
if (save[i + 1]) {
// should be save[1].username ("test1")
console.log("2: " + save[i + 1].username); // output "test1"
}
/*
* creating reference
* so chat.users[i + 1] is now save[i] ({ username: "test" })
* and because save is reference of chat.users, save[i + 1] is now also now save[i] ({ username: "test" })
*/
chat.users[i + 1] = save[i];
if (chat.users[i + 1]) {
// should be chat.users[1].username ("test")
console.log("3: " + chat.users[i + 1].username); // output "test"
}
if (save[i + 1]) {
// should be chat.users[0].username ("test")
console.log("4: " + save[i].username); // output "test"
}
什么?
让我再给你解释一下。例如你得到了这个:
var a = [1, 2];
现在你写这个:
var b = a;
也许您想将 a 复制到 b 但您只创建了一个参考!
所以看看这个:
console.log(a, b);
//=> [1, 2] [1, 2]
a[0] = 3;
console.log(a, b);
//=> [3, 2] [3, 2]
b[0] = 4;
console.log(a, b);
//=> [4, 2] [4, 2]
因此,如果您更改对象或数组的一个值,则另一个值也会更改,因为它只是一个引用,并且它们都具有相同的内存地址。
如果你真的想克隆/复制对象/数组,那么看看这个问题。