如何在JS数组的任何位置插入新元素? [英] How to insert a new element at any position of a JS array?

查看:65
本文介绍了如何在JS数组的任何位置插入新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 [a,b,c] .我希望能够在该数组的每个元素之间插入一个值,例如: [0,a,0,b,0,c,0] .

I have an array [a, b, c]. I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0].

我想可能是这样,但我无法使其正常工作.

I guess it would be something like this, but I can't make it works.

for (let i = 0; i < array.length; i++) {
    newArray = [
        ...array.splice(0, i),
        0,
        ...array.splice(i, array.length),
    ];
}

谢谢您的帮助!

推荐答案

要获取新数组,可以连接零件并为每个元素添加零元素.

For getting a new array, you could concat the part an add a zero element for each element.

var array = ['a', 'b', 'c'],
    result = array.reduce((r, a) => r.concat(a, 0), [0]);
    
console.log(result);

使用相同的数组

var array = ['a', 'b', 'c'],
    i = 0;

while (i <= array.length) {
    array.splice(i, 0, 0);
    i += 2;
}

console.log(array);

从结尾开始迭代要短一些.

A bit shorter with iterating from the end.

var array = ['a', 'b', 'c'],
    i = array.length;

do {
    array.splice(i, 0, 0);
} while (i--)

console.log(array);

这篇关于如何在JS数组的任何位置插入新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆