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

后端 未结 20 2125
灰色年华
灰色年华 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 08:07

    What you want is the splice function on the native array object.

    arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

    In this example we will create an array and add an element to it into index 2:

    var arr = [];
    arr[0] = "Jani";
    arr[1] = "Hege";
    arr[2] = "Stale";
    arr[3] = "Kai Jim";
    arr[4] = "Borge";
    
    console.log(arr.join());
    arr.splice(2, 0, "Lene");
    console.log(arr.join());

提交回复
热议问题