Page 1 of 1
unlogic js
Posted: Tue Nov 13, 2012 4:49 pm
by Ark
Hi, this is something very unusual I've found about javascript when using arrays. But i'll explain better in the following image:
So i'm making an array of arrays. But when I modified just the first value of the first array, magically all of the arrays are modified. Does anybody knows why? Maybe i'm wrong but I just don't undestand why ...
But when I do it in another way, it works as expected:

Re: unlogic js
Posted: Tue Nov 13, 2012 11:37 pm
by jwalton922
In the first example, each index of b is referring to the same reference so any change to that reference will be reflected at each index of b. If you created a in the for loop, you'd have 3 separate arrays :
for(var i = 0; i < 3; i++){
var a = [0,0,0];
b.push(a); //alternatively: b.push([0,0,0])
}
In the second example, you are creating three separate arrays, so modifying one has no effect on the other.
Re: unlogic js
Posted: Wed Nov 14, 2012 3:17 am
by Ark
Ohh interesting! (My whole life was a lie). Thanks for clearing it up now I can die peacefully.
Re: unlogic js
Posted: Wed Nov 14, 2012 3:57 am
by Jackolantern
This behavior is because arrays in Javascript are objects, not actual primitive arrays. Just like any other object, you can store references to the object in multiple variables, but each of those references all point to the same object, and a change through one reference changes "them all".
It seems weird, but once you get used to it, the heavy object-centric focus of Javascript can be extremely powerful.