因此,例如,我有以下数组
var sections = [{ name: 'apple', count: 20 },
{ name: 'banana', count: 80 },
{ name: 'oranges', count: 10 }]
现在,如果我想添加更多项目,那么我可以
sections.push({ name: 'mango', count: '32' });
这会将新数组添加到节中。
现在,假设我有另一个数组来显示水果的来源和数量。
var country = [{ country: 'usa', count: 5 },
{ country: 'brazil', count: 27 }]
因此,我想用一个名为country的新道具将这个新country
数组添加到第三个元素中sections
,如下所示。
var sections = [{ name: 'apple', count: 20 },
{ name: 'banana', count: 80 },
{ name: 'oranges', count: 10,
country: [{ country: 'usa', count: 5 },
{ country: 'brazil', count: 27 }]
}]
我怎样才能做到这一点?我尝试过push
,splice
但根本无法解决。
我还尝试了section [3] .push.apply(country)..和许多其他我不记得的事情。我收到了一个错误或者只是没有按我的意愿推送数组。
您可以尝试这样的事情:
sections[2].country = country;
在这里,sections[2]
我们偷看了对的第三项的引用sections
。然后,我们定义一个名为的属性,country
并为其分配所需的值。
为什么推不起作用?
push是一种数组方法,使您能够将元素推入数组的末尾。如果您尝试使用推入sections[2]
将不起作用,因为sections[2]
不是数组。对于splice
,这也是一个数组方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句