推入数组中的对象 [英] Push Object in Array

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

问题描述

 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})

对数组中的对象进行常规的推入操作,并在插入后更新索引.

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天全站免登陆