Pushing objects to an array, then modifying them,

2019-09-20 03:53发布

This question already has an answer here:

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条回答
虎瘦雄心在
2楼-- · 2019-09-20 04:10

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;
}
查看更多
登录 后发表回答