2017-10-12 77 views
0

我需要在每个第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个位置上做到这一点。

+1

而不是改变实际的数组,你可以从它生成一个新的 – Faly

回答

1

只需将您的代码更改为此即可。将3添加到itemIndex以解释1插入。

var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
 
for (var itemIndex = 2; itemIndex < dataRow.length; itemIndex += 3) { 
 
    
 
    dataRow.splice(itemIndex, 0, 'insert this'); 
 
} 
 

 
console.log(dataRow);

+0

就是这样,谢谢 – cincplug

1

你可以从最终迭代和拼接额外的项目。

var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
 
for (var itemIndex = Math.floor(dataRow.length/2) * 2; itemIndex > 0; itemIndex -= 2) { 
 
    dataRow.splice(itemIndex, 0, 'insert this'); 
 
} 
 

 
console.log(dataRow);

1

var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
 
var length = dataRow.length; 
 
for (var i = 1; i <= length/2; i++) { 
 
    dataRow.splice(i * 3 - 1, 0, 'insert this'); 
 
} 
 
console.log(dataRow);

希望这个作品!

相关问题