Javascript | 如何从索引x开始每n个元素向数组添加一个元素?

说我有一个数组:


var cars = ["Saab", "Volvo", "BMW", "Audi", "Nissan", "Ford"];

我想"Triumph"从索引2开始每2个元素添加另一个元素,给我这个


cars

["Saab", "Volvo", "Triumph", "BMW", "Audi", "Triumph", "Nissan", "Ford", "Triumph"];

我已经试过了:


for (let [index, val] of cars.entries()) {

    if (index % 2 == 0) {

        cars.splice(index, 0, "")

    }

}

但是它每隔一个元素就添加一个新元素,而不是每隔2个元素,并且我不确定如何使它从特定索引开始


[ '', 'Saab', '', 'Volvo', '', 'BMW', '', 'Audi', '', 'Nissan', '', 'Ford']


梵蒂冈之花
浏览 223回答 1
1回答

浮云间

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

相关分类

JavaScript