現在你的代碼很清楚!讓我們來看看它
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;
也許你想要一個複製到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]
所以,如果你改變它會爲另一隻也被改變的對象或數組的一個值,因爲它只是一個參考,他們都得到了相同的內存地址。
如果你真的想克隆/複製對象/數組,然後看看this question。
好的,我做到這一點,這就是工程 \t \t \t \t \t如果(溫度[0])溫度[1] =溫度[0]; \t \t \t \t \t else temp [1] = save [i]; \t \t \t \t \t if(save [i + 1])temp [0] = save [i + 1]; \t \t \t \t \t chat.users [i + 1] = temp [1]; – Ajouve