The best way to remove array element by value

后端 未结 10 1344
北荒
北荒 2020-12-25 10:18

I have an array like this

arr = [\"orange\",\"red\",\"black\",\"white\"]

I want to augment the array object defining a deleteElem()<

10条回答
  •  醉酒成梦
    2020-12-25 10:23

    The best way is to use splice and rebuild new array, because after splice, the length of array does't change.

    Check out my answer:

    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

提交回复
热议问题