Pushing objects to an array, then modifying them, makes all object properties the same [duplicate]

巧了我就是萌 提交于 2019-12-25 18:27:54

问题


When I run this code:

var e = {
  'id': 0,
  'name': 'n'
};
var data = [];

for (var i = 0; i < 3; i++) {
  e.id = i;
  data.push(e);
}

console.log(data);

I expect data to look like this:

[
  {
    'id': 0,
    'name': 'n'
  },
  {
    'id': 1,
    'name': 'n'
  },
  {
    'id': 2,
    'name': 'n'
  }
]

but the actual result is:

[
  {
    'id': 2,
    'name': 'n'
  },
  {
    'id': 2,
    'name': 'n'
  },
  {
    'id': 2,
    'name': 'n'
  }
]

Why does this happen and how to fix this?


回答1:


The problem is that you've pushing the same object multiple times and editing it.

Try defining e inside the loop:

var data=[];
for(var i=0;i<10;i++)
{
    var e={'id':i,'name':'n'};
    data.push(e);
}

Or with cloning (uses jquery):

var data=[];
var e={'id':0,'name':'n'};
for(var i=0; i<10; i++)
{
    var e_copy = jQuery.extend({}, e); // or clone(e)
    e_copy.id=i;
    data.push(e);
}

Roll your own cloning fn:

function clone(o){
    var o_copy = {}; 
    for (var p in o) {
        if (o.hasOwnProperty(p)){
            o_copy[p] = o[p]
        }
    }
    return o_copy;
}


来源:https://stackoverflow.com/questions/31165111/pushing-objects-to-an-array-then-modifying-them-makes-all-object-properties-th

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