Deleting array elements in JavaScript - delete vs splice

后端 未结 27 3595
予麋鹿
予麋鹿 2020-11-21 05:31

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?

For example:

myArray = [\         


        
27条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:18

    delete: delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

    splice: actually removes the element, reindexes the array, and changes its length.

    Delete element from last

    arrName.pop();
    

    Delete element from first

    arrName.shift();
    

    Delete from middle

    arrName.splice(starting index,number of element you wnt to delete);
    
    Ex: arrName.splice(1,1);
    

    Delete one element from last

    arrName.splice(-1);
    

    Delete by using array index number

     delete arrName[1];
    

提交回复
热议问题