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

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

    Other than splice, you can use this approach which will not mutate the original array, but will create a new array with the added item. You should usually avoid mutation whenever possible. I'm using ES6 spread operator here.

    const items = [1, 2, 3, 4, 5]
    
    const insert = (arr, index, newItem) => [
      // part of the array before the specified index
      ...arr.slice(0, index),
      // inserted item
      newItem,
      // part of the array after the specified index
      ...arr.slice(index)
    ]
    
    const result = insert(items, 1, 10)
    
    console.log(result)
    // [1, 10, 2, 3, 4, 5]

    This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well

    const items = [1, 2, 3, 4, 5]
    
    const insert = (arr, index, ...newItems) => [
      // part of the array before the specified index
      ...arr.slice(0, index),
      // inserted items
      ...newItems,
      // part of the array after the specified index
      ...arr.slice(index)
    ]
    
    const result = insert(items, 1, 10, 20)
    
    console.log(result)
    // [1, 10, 20, 2, 3, 4, 5]

提交回复
热议问题