1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
我建議您使用反向迭代,這樣您就不會(huì)修改要迭代的同一數(shù)組,因?yàn)檫@會(huì)改變索引。
另外,您可能想實(shí)現(xiàn)一個(gè)簡單的邊緣情況,以確定是否需要在該字符串的末尾添加一個(gè)字符串。這可以通過查看數(shù)組本身是否可以被要跳過的項(xiàng)目數(shù)整除來完成。
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 );
添加回答
舉報(bào)