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

后端 未结 17 1259
清歌不尽
清歌不尽 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:58

    Another way if you want to exclude the start and end of array is :

    var arr = ['a', 'b', 'c']
    var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b))
    
    console.log(newArr)

提交回复
热议问题