问题
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