2

Why is the array getting just the last object?

this.checkpoints = new Array();

this.checkpoint = new Object();
    this.checkpoint['lat'];
    this.checkpoint['lng'];

this.checkpoint['lat'] = 1;
this.checkpoint['lng'] = 1;
this.checkpoints.push(this.checkpoint);

this.checkpoint['lat'] = 2;
this.checkpoint['lng'] = 2;
this.checkpoints.push(this.checkpoint);

this.checkpoint['lat'] = 3;
this.checkpoint['lng'] = 3;
this.checkpoints.push(this.checkpoint);

console.log(this.checkpoints);

The result is wrong:

[Object { lat=3,  lng=3}, Object { lat=3,  lng=3}, Object { lat=3,  lng=3}]

But if I try without objects, it's OK:

this.checkpoints = new Array();

this.checkpoints.push(1);

this.checkpoints.push(2);

this.checkpoints.push(3);

console.log(this.checkpoints);

The result is:

[1, 2, 3]

Please, what am I missing? Thanks in advance!

4
  • 1
    It's because the pushing is reference based. It pushes this.checkpoint's address (reference), not it's value. Commented May 18, 2015 at 6:58
  • I wonder what this :this.checkpoint['lat']; this.checkpoint['lng']; do Commented May 18, 2015 at 6:59
  • @RoyiNamir It means you are assigning properties to the object with those names. Commented May 18, 2015 at 7:01
  • @RaeenHashemi it was not a question but pointing to a non code : i.imgur.com/bcVR8o6.png ( line 3 & 4 at OP's code) Commented May 18, 2015 at 7:02

2 Answers 2

4

Because you are just changing the property values of the same object. You need to create 3 different objects.

You can simplify it using Object Initializer

this.checkpoints = new Array();

this.checkpoints.push({
    lat: 1,
    lng: 1
});
this.checkpoints.push({
    lat: 2,
    lng: 2
});
this.checkpoints.push({
    lat: 3,
    lng: 3
});

console.log(this.checkpoints);
Sign up to request clarification or add additional context in comments.

Comments

0

this.checkpoint = new Object();
    this.checkpoint['lat'];
    this.checkpoint['lng'];

this.checkpoint['lat'] = 1;
this.checkpoint['lng'] = 1;
this.checkpoints.push(this.checkpoint);

this.checkpoint['lat'] = 2;
this.checkpoint['lng'] = 2;
this.checkpoints.push(this.checkpoint);

this.checkpoint['lat'] = 3;
this.checkpoint['lng'] = 3;
this.checkpoints.push(this.checkpoint);
it only changes the checkpoint['lat'] , checkpoint['lng'] property of the checkpoints object so when you execute the

" console.log(this.checkpoints);" statement

it will display only the last changed property value and that is 3 for both ['lat'] and ['lng'] former values are overridden by last one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.