Deleting array elements in JavaScript - delete vs splice

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

    function remove_array_value(array, value) {
        var index = array.indexOf(value);
        if (index >= 0) {
            array.splice(index, 1);
            reindex_array(array);
        }
    }
    function reindex_array(array) {
       var result = [];
        for (var key in array) {
            result.push(array[key]);
        }
        return result;
    }
    

    example:

    var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
    remove_array_value(example_arr, 'banana');
    

    banana is deleted and array length = 2

提交回复
热议问题