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

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

    I recommend using pure JavaScript in this case, also there is no insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you, it's called splice...

    Let's see what's splice()...

    The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

    OK, imagine we have this array below:

    const arr = [1, 2, 3, 4, 5];
    

    We can remove 3 like this:

    arr.splice(arr.indexOf(3), 1);
    

    It will return 3, but if we check the arr now, we have:

    [1, 2, 4, 5]
    

    So far, so good, but how we can add a new element to array using splice? Let's put back 3 in the arr...

    arr.splice(2, 0, 3);
    

    Let's see what we have done...

    We use splice again, but this time for the second argument, we pass 0, means we want to delete no item, but at the same time, we add third argument which is 3 that will be added at second index...

    You should be aware, that we can delete and add at the same time, for example now we can do:

    arr.splice(2, 2, 3);
    

    Which will delete 2 items at index 2, then add 3 at index 2 and result will be:

    [1, 2, 3, 5];
    

    This is showing how each item in splice work:

    array.splice(start, deleteCount, item1, item2, item3 ...)

提交回复
热议问题