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

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

    Append Single Element at a specific index

    //Append at specific position(here at index 1)
    arrName.splice(1, 0,'newName1');
    //1: index number, 0: number of element to remove, newName1: new element
    
    
    //Append at specific position (here at index 3)
    arrName[3] = 'newName1';
    

    Append Multiple Element at a specific index

    //Append from index number 1
    arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
    //1: index number from where append start, 
    //0: number of element to remove, 
    //newElemenet1,2,3: new elements
    

提交回复
热议问题