gpt4 book ai didi

arrays - 数组变量修改node.js

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:28 24 4
gpt4 key购买 nike

我不明白为什么我的变量会改变

if(chat.users[i + 1])
console.log("1: " + chat.users[i + 1].username);
if(save[i+1])
console.log("2: " + save[i + 1].username);

chat.users[i + 1] = save[i];

if(chat.users[i + 1])
console.log("3: " + chat.users[i + 1].username);
if(save[i+1])
console.log("4: " + save[i + 1].username);

我有

1: test1
2: test1
3: test
4: test

我不明白为什么我没有

1: test1
2: test1
3: test
4: test1

谢谢

编辑:所有代码都在那里

http://codepaste.net/gi5ghf(第 92 行)

最佳答案

现在你的代码就清楚了!我们来看看吧

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]

因此,如果您更改对象或数组的一个值,另一个值也会更改,因为它只是一个引用,并且它们都具有相同的内存地址。

如果您确实想克隆/复制对象/数组,请查看 this question .

关于arrays - 数组变量修改node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13810974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com