如何在javascript中将对象附加到数组?

时间:2015-05-18 06:55:33

标签: javascript 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);

结果是错误的:

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

但如果我尝试没有物体,那就没关系:

this.checkpoints = new Array();

this.checkpoints.push(1);

this.checkpoints.push(2);

this.checkpoints.push(3);

console.log(this.checkpoints);

结果是:

[1, 2, 3]

拜托,我错过了什么?提前谢谢!

2 个答案:

答案 0 :(得分:4)

因为您只是更改同一对象的属性值。您需要创建3个不同的对象。

您可以使用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);

答案 1 :(得分: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);



  它只会更改检查点对象的检查点[' lat'],检查点[' lng']属性,因此当您执行

"的console.log(this.checkpoints);"声明

它将仅显示最后更改的属性值,对于[' lat']和[' lng'],前一个值将被最后一个覆盖。