JordyV
JordyV

Reputation: 389

Trouble with populating an array

It's very basic, but I just don't see what I'm missing here..

Consider the next array objects. It needs to be filled with instances of object which each have their own id:

var objects= [];
var object= {};

object.id = 1;
objects[0] = object;
object.id = 2;
objects[1] = object;
object.id = 3;
objects[2] = object;

When I alert the first object with alert(objects[0].id), it says 3. Again, what am I missing here?

Upvotes: 0

Views: 64

Answers (2)

gen_Eric
gen_Eric

Reputation: 227310

This is because you are pushing the same object into each spot in the array. You need to make new ones each time.

var objects = [];

objects[0] = {id: 1};
objects[1] = {id: 2};
objects[2] = {id: 3};

Or better yet, just make it all at once:

var objects = [
    {id: 1},
    {id: 2},
    {id: 3},
];

Upvotes: 7

Shryme
Shryme

Reputation: 1570

It save the object as reference so as soon as you change the id, it changes it for everything. To solve it you can simply do

object.id = 1;
objects[0] = object;
object = {};

Upvotes: 5

Related Questions