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

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

    Immutable insertion

    Using splice method is surely the best answer if you need to insert into an array in-place.

    However, if you are looking for an immutable function that returns a new updated array instead of mutating the original array on insert, you can use the following function.

    function insert(array, index) {
      const items = Array.prototype.slice.call(arguments, 2);
    
      return [].concat(array.slice(0, index), items, array.slice(index));
    }
    
    const list = ['one', 'two', 'three'];
    
    const list1 = insert(list, 0, 'zero'); // Insert single item
    const list2 = insert(list, 3, 'four', 'five', 'six'); // Insert multiple
    
    
    console.log('Original list: ', list);
    console.log('Inserted list1: ', list1);
    console.log('Inserted list2: ', list2);

    Note: This is a pre-ES2015 way of doing it so it works for both older and newer browsers.

    If you're using ES6 then you can try out rest parameters too; see this answer.

提交回复
热议问题