How to insert an item into an array at a specific index (JavaScript)?

后端 未结 20 2116
灰色年华
灰色年华 2020-11-21 07:05

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any JavaScript implem

20条回答
  •  借酒劲吻你
    2020-11-21 07:46

    Taking profit of reduce method as following:

    function insert(arr, val, index) {
        return index >= arr.length 
            ? arr.concat(val)
            : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
    }
    

    So at this way we can return a new array (will be a cool functional way - more much better than use push or splice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.

提交回复
热议问题