我需要在每个第n个成员之后向JavaScript数组中插入一个新成员。Javascript:在每个第n个成员之后插入数组的新成员
如果我尝试迭代数组并插入新成员array.splice()
,它不起作用,因为任何类型的迭代循环都依赖于数组长度,数组长度在每次迭代时都会发生变化。例如,我有数组,如:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
,并希望把它想:
[1, 2, 'insert this', 3, 4, 'insert this', 5, 6, 'insert this', 7, 8, 'insert this', 9, 10, 'insert this']
如果我尝试下面的代码,我结束了空数组:
var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var itemIndex = 2; itemIndex < dataRow.length; itemIndex += 2) {
dataRow.splice(itemIndex, 0, 'insert this');
}
这问题不是人们只想获得数组成员或将其插入到某个特定位置的问题的重复。问题是,如何在每个第n个位置上做到这一点。
而不是改变实际的数组,你可以从它生成一个新的 – Faly