Push Object in Array [duplicate]

笑着哭i 提交于 2020-01-09 03:55:08

问题


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

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.

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


回答1:


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>



回答2:


You can also create a function that will create clone for the Object:

JSON.clone = function(json) {
    var
        temp = null,
        key = null;

    if (json === null || typeof json !== 'object') {
        return json;
    }
    temp = json.constructor(); // changed
    for (key in json) {
        if (json.hasOwnProperty(key)) {
            temp[key] = JSON.clone(json[key]);
        }
    }
    return temp;
};

Then you can use your original code but with little changes:

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


来源:https://stackoverflow.com/questions/32175356/push-object-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!