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:
unlogic js
-
- Posts: 21
- Joined: Thu Jul 12, 2012 11:28 pm
Re: unlogic js
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.
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
Ohh interesting! (My whole life was a lie). Thanks for clearing it up now I can die peacefully.
Orgullo Catracho
- Jackolantern
- Posts: 10893
- Joined: Wed Jul 01, 2009 11:00 pm
Re: unlogic js
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.
It seems weird, but once you get used to it, the heavy object-centric focus of Javascript can be extremely powerful.
The indelible lord of tl;dr