unlogic js

Need help with an engine or coding not on the list? Need help with a game or the website and forums here? Direct all questions here.
Post Reply
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

unlogic js

Post 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:

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:

Image
Orgullo Catracho
jwalton922
Posts: 21
Joined: Thu Jul 12, 2012 11:28 pm

Re: unlogic js

Post 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.
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: unlogic js

Post by Ark »

Ohh interesting! (My whole life was a lie). Thanks for clearing it up now I can die peacefully.
Orgullo Catracho
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Re: unlogic js

Post 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.
The indelible lord of tl;dr
Post Reply

Return to “Advanced Help and Support”