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

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

    Here are two ways :

    const array = [ 'My', 'name', 'Hamza' ];
    
    array.splice(2, 0, 'is');
    
    console.log("Method 1 : ", array.join(" "));

    OR

    Array.prototype.insert = function ( index, item ) {
        this.splice( index, 0, item );
    };
    
    const array = [ 'My', 'name', 'Hamza' ];
    array.insert(2, 'is');
    
    console.log("Method 2 : ", array.join(" "));

提交回复
热议问题