Deleting array elements in JavaScript - delete vs splice

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

    delete acts like a non real world situation, it just removes the item, but the array length stays the same:

    example from node terminal:

    > var arr = ["a","b","c","d"];
    > delete arr[2]
    true
    > arr
    [ 'a', 'b', , 'd', 'e' ]
    

    Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1

    function(arr,arrIndex){
        return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
    }
    

    What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.

    Here is an example using the function above as a node module, seeing the terminal will be useful:

    > var arr = ["a","b","c","d"]
    > arr
    [ 'a', 'b', 'c', 'd' ]
    > arr.length
    4 
    > var arrayRemoveIndex = require("./lib/array_remove_index");
    > var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
    > newArray
    [ 'a', 'b', 'd' ] // c ya later
    > newArray.length
    3
    

    please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.

提交回复
热议问题