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

后端 未结 20 2175
灰色年华
灰色年华 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:50

    If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

    Also here are some functions to illustrate both examples:

    function insertAt(array, index) {
        var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
        return insertArrayAt(array, index, arrayToInsert);
    }
    
    function insertArrayAt(array, index, arrayToInsert) {
        Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
        return array;
    }
    

    Finally here is a jsFiddle so you can see it for youself: http://jsfiddle.net/luisperezphd/Wc8aS/

    And this is how you use the functions:

    // if you want to insert specific values whether constants or variables:
    insertAt(arr, 1, "x", "y", "z");
    
    // OR if you have an array:
    var arrToInsert = ["x", "y", "z"];
    insertArrayAt(arr, 1, arrToInsert);
    

提交回复
热议问题