Reputation: 10089
I can't understand why my variable change
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);
I have
1: test1
2: test1
3: test
4: test
I can't understand why I don't have
1: test1
2: test1
3: test
4: test1
Thanks
Edit: The all code is there
http://codepaste.net/gi5ghf (line 92)
Upvotes: 1
Views: 168
Reputation: 9202
Now with your code it's clear! Let's have a look at it
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"
}
What?
Let me explain it to you again. For example you got this:
var a = [1, 2];
Now you write this:
var b = a;
Maybe you wanted to copy a to b but you ONLY created a reference!
So have a look at this:
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]
So if you change one value of the object or array it'll be changed for the other one too because it's only a reference and they both got the same memory address.
If you really Want to clone/copy the object/array then have a look at this question.
Upvotes: 1
Reputation: 7522
save[i] appears to be a user with a username of 'test'. You are assigning this user to chat.users[i + 1]:
chat.users[i + 1] = save[i];
You are then printing out it its username:
if(chat.users[i + 1]) console.log("3: "+chat.users[i + 1].username);
Finally, you are printing out save[i]'s username:
if(save[i+1]) console.log("4: "+save[i].username);
It prints out 'test', because that's what save[i]'s username is.
Perhaps you meant that last line to print out save[i + 1]'s username, not save[i]'s username? save[i + 1] does have a username of 'test1'.
Upvotes: 0