Deleting array elements in JavaScript - delete vs splice

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

    The difference can be seen by logging the length of each array after the delete operator and splice() method are applied. For example:

    delete operator

    var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
    delete trees[3];
    
    console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
    console.log(trees.length); // 5
    

    The delete operator removes the element from the array, but the "placeholder" of the element still exists. oak has been removed but it still takes space in the array. Because of this, the length of the array remains 5.

    splice() method

    var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
    trees.splice(3,1);
    
    console.log(trees); // ["redwood", "bay", "cedar", "maple"]
    console.log(trees.length); // 4
    

    The splice() method completely removes the target value and the "placeholder" as well. oak has been removed as well as the space it used to occupy in the array. The length of the array is now 4.

提交回复
热议问题