【发布时间】:2016-06-17 11:43:41
【问题描述】:
我有以下代码:
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.push(list2);
我希望得到以下结果:
列表1:
- 0:对象(苏黎世)
- 1:对象(伦敦)
- 3:对象(纽约)
- 4:对象(虚拟)
- 5:对象(Dummy2)
但我得到了这个:
列表1:
- 0:对象(苏黎世)
- 1:对象(伦敦)
- 2:对象(纽约)
- 3:对象(项目)
- 0:对象(虚拟)
- 1:对象(虚拟 2)
我怎样才能得到我的预期结果?
感谢和欢呼。
【问题讨论】:
-
您提供的代码
list1.push(list2);将失败并出现TypeError。为什么你期望4: Object (Items)而不是4: Object (Dummy)? -
@squint 那是一个错字...而且我没有遇到错误,它会打印我的第二个结果以防我的预期..但是使用 concat 它可以工作..
-
list1没有.push()方法,所以你必须在做其他事情。.push()和.concat()方法非常不同。一个突变,另一个替换。在某些情况下,这可能是一个重要的区别。 -
关于
.apply()的问题,您需要将list1.Items设置为.push()的“this”值,这样您就可以将list2.Items的成员作为单独的args传递。你可以这样做:Array.prototype.push.apply(list1.Items, list2.Items)或list1.Items.push.apply(list1.Items, list2.Items)。那些有效地使电话最终像您一样:list1.Items.push(list2.Items[0], list2.Items[1], ...and so on... ) -
是的,就是这样,只不过@987654336@构造了一个新的Array只是为了访问
.push(),这看起来很浪费。您已经有一个带有list1.Items的数组,或者您可以使用Array.prototype.push获取该方法。
标签: javascript jquery object push