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

后端 未结 20 2493
灰色年华
灰色年华 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:52

    Array#splice() is the way to go, unless you really want to avoid mutating the array. Given 2 arrays arr1 and arr2, here's how you would insert the contents of arr2 into arr1 after the first element:

    const arr1 = ['a', 'd', 'e'];
    const arr2 = ['b', 'c'];
    
    arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']
    
    console.log(arr1)

    If you are concerned about mutating the array (for example, if using Immutable.js), you can instead use slice(), not to be confused with splice() with a 'p'.

    const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];
    

提交回复
热议问题