在数组中推送对象

Kun*_*ist 2 javascript arrays object

 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);
Run Code Online (Sandbox Code Playgroud)

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

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

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

T.J*_*der 9

您正在将相同的对象重复推入数组,并且只需更新该id对象的属性即可.

如果您想在数组中使用多个对象,则需要创建多个对象:

var copyArray = [];
while (copyArray.length < 3) {
  copyArray.push({
    id: copyArray.length
  });
}
snippet.log(JSON.stringify(copyArray));
Run Code Online (Sandbox Code Playgroud)
<!-- 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>
Run Code Online (Sandbox Code Playgroud)