【发布时间】:2018-01-24 10:26:52
【问题描述】:
在初始阶段,我有一个对象数组:
[
{ type: 'all' },
{ type: 'all' },
{ type: 'all' },
{ type: 'fruit'},
{ type: 'all' },
{ type: 'all' },
{ type: 'fruit' },
{ type: 'all' },
{ type: 'all' },
{ type: 'fruit' },
{ type: 'fruit' }
]
我要插入:
1) 对象:{type: 'toys'} 在每 5 个类型为 all 的项目中
2) 对象:{type: 'clothes'} 在每 2 个类型为 'fruit' 的项目中
预期结果:
[
{ type: 'all' },
{ type: 'all' },
{ type: 'all' },
{ type: 'fruit'},
{ type: 'all' },
{ type: 'all' },
{ type: 'toys' },
{ type: 'fruit' },
{ type: 'clothes' },
{ type: 'all' },
{ type: 'all' },
{ type: 'fruit' },
{ type: 'fruit' },
{ type: 'clothes' }
]
我该如何实现这个功能?我尝试 forEach 添加项目,但是在推送一个项目后,array_demo 长度发生了变化,很难测量哪个是列表的下一个原始项目。
array_demo.forEach((item, index) => {
array_demo.push({type: 'demo'});
console.warn(index);
});
【问题讨论】:
-
在另一个阵列上做而不是在原地做
标签: javascript arrays add