将对象推入数组,然后对其进行修改,使所有对象属性相同 [英] Pushing objects to an array, then modifying them, makes all object properties the same
本文介绍了将对象推入数组,然后对其进行修改,使所有对象属性相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行此代码时:
var e = {
'id': 0,
'name': 'n'
};
var data = [];
for (var i = 0; i < 3; i++) {
e.id = i;
data.push(e);
}
console.log(data);
我希望data
看起来像这样:
[
{
'id': 0,
'name': 'n'
},
{
'id': 1,
'name': 'n'
},
{
'id': 2,
'name': 'n'
}
]
但实际结果是:
[
{
'id': 2,
'name': 'n'
},
{
'id': 2,
'name': 'n'
},
{
'id': 2,
'name': 'n'
}
]
为什么会发生这种情况以及如何解决?
Why does this happen and how to fix this?
推荐答案
问题是您多次推送相同的对象并对其进行编辑.
The problem is that you've pushing the same object multiple times and editing it.
尝试在循环内定义e:
var data=[];
for(var i=0;i<10;i++)
{
var e={'id':i,'name':'n'};
data.push(e);
}
或克隆(使用jquery):
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);
}
滚动您自己的克隆fn:
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;
}
这篇关于将对象推入数组,然后对其进行修改,使所有对象属性相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文