Deleting array elements in JavaScript - delete vs splice

后端 未结 27 4421
予麋鹿
予麋鹿 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:10

    Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

    The following code will display "a", "b", "undefined", "d"

    myArray = ['a', 'b', 'c', 'd']; delete myArray[2];
    
    for (var count = 0; count < myArray.length; count++) {
        alert(myArray[count]);
    }
    

    Whereas this will display "a", "b", "d"

    myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);
    
    for (var count = 0; count < myArray.length; count++) {
        alert(myArray[count]);
    }
    

提交回复
热议问题