How to insert a new element in between all elements of a JS array?

后端 未结 17 1226
清歌不尽
清歌不尽 2020-12-29 20:38

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 gues

17条回答
  •  再見小時候
    2020-12-29 20:53

    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);

    Using the same array

    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);

提交回复
热议问题