Delete an array key when it contains a string in javascript

前端 未结 2 1752
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 17:19

I have an array in javascript that looks like this:

arr = [\"md51234\",\"md55234\"]

I\'m trying to remove an item from this by doing:

相关标签:
2条回答
  • 2021-01-07 18:09

    Different approach using jQuery:

    arr = ["a", "b", "c", "d", "e"];
    

    Remove item by index:

    arr = jQuery.grep(arr, function(value, index) {
        return index != 2;
    });
    

    Remove item by value:

    arr = jQuery.grep(arr, function(value, index) {
        return value != "a";
    });
    
    0 讨论(0)
  • 2021-01-07 18:20

    You must provide the index, not the value :

    delete arr[0];
    

    Alternatively, you could also use indexOf on most browsers

    delete arr[arr.indexOf("md51234")];
    

    But note that delete doesn't make the array shorter, it just make a value undefined. Your array after having used delete is

    [undefined, "md55234"]
    

    If you want to make the array shorter, use

    arr.splice(0, 1); // first parameter is index of element to remove, second one is number of elements to  remove
    

    This makes

    ["md55234"]
    
    0 讨论(0)
提交回复
热议问题