1 回答
TA贡献1829条经验 获得超4个赞
我建议您使用反向迭代,这样您就不会修改要迭代的同一数组,因为这会改变索引。
另外,您可能想实现一个简单的边缘情况,以确定是否需要在该字符串的末尾添加一个字符串。这可以通过查看数组本身是否可以被要跳过的项目数整除来完成。
const cars = ["Saab", "Volvo", "BMW", "Audi", "Nissan", "Ford"];
const insertAfterN = (arr, n, str) => {
let newArray = [...arr];
const addToEnd = newArray.length % n === 0;
for (let i = newArray.length - 1; i >= 0; i--)
if (i % 2 == 0 && i !== 0) newArray.splice(i, 0, str)
if (addToEnd) newArray.push(str);
return newArray;
}
//Insert <"Triumph"> into the <cars> array after every <2> items
const result = insertAfterN(cars, 2, "Triumph");
console.log( result );
如果您想更简洁一些,可以使用reduce():
const cars = ["Saab", "Volvo", "BMW", "Audi", "Nissan", "Ford"];
const insertAfterN = (arr, n, str) => {
const addToEnd = arr.length % n === 0;
const result = arr.reduce((a,i,idx) => { idx && !(idx%n) ? a.push(str,i) : a.push(i); return a; }, []);
if (addToEnd) result.push(str);
return result;
}
//Insert <"Triumph"> into the <cars> array after every <2> items
const result = insertAfterN(cars, 2, "Triumph");
console.log( result );
添加回答
举报