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

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

    You can implement the Array.insert method by doing this:

    Array.prototype.insert = function ( index, item ) {
        this.splice( index, 0, item );
    };
    

    Then you can use it like:

    var arr = [ 'A', 'B', 'D', 'E' ];
    arr.insert(2, 'C');
    
    // => arr == [ 'A', 'B', 'C', 'D', 'E' ]
    

提交回复
热议问题