在数组中推送对象 [英] Push Object in Array

查看:32
本文介绍了在数组中推送对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 var p = {
     id: null
 };
 for (var copyArray = [], i = 0; i < 3; i++) {
     copyArray.push(p);
     copyArray[i].id = (copyArray.length) - parseInt(1, 10);
 }
 console.log(copyArray);

copyArray 中的所有 id 都获得 2 个值.结果 CopyArray({id=2},{id=2},{id=2})

All id in copyArray is getting 2 value. Result CopyArray({id=2},{id=2},{id=2})

对数组中的对象进行正常的push操作,插入后更新索引.

Doing normal push operation of object in array, and updating the index after insertion.

但不知何故复制数组中的所有 id 都获得相同的 id我在这里做错了什么

But somehow all id's in the copy array are getting same id What wrong i am doing over here

推荐答案

您重复地将 相同对象 推入数组,并且只是更新了 id 属性随你去的那个对象.

You're pushing the same object into the array repeatedly, and just updating the id property on that object as you go.

如果你想要数组中有多个对象,你需要创建多个对象:

If you want multiple objects in the array, you'll need to create multiple objects:

var copyArray = [];
while (copyArray.length < 3) {
  copyArray.push({
    id: copyArray.length
  });
}
snippet.log(JSON.stringify(copyArray));

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这篇关于在数组中推送对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆