繁体   English   中英

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

[英]How to append an object to array in javascript?

为什么数组只得到最后一个对象?

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]

拜托,我想念什么? 提前致谢!

因为您只是在更改同一对象的属性值。 您需要创建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);

 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); 
它只会更改checkpoints对象的checkpoint ['lat']和checkpoint ['lng']属性,因此当您执行

“ console.log(this.checkpoints);” 声明

它将仅显示最后更改的属性值,对于['lat']和['lng']先前的值,该值均为3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM