remove string element from javascript array

前端 未结 4 1552
我在风中等你
我在风中等你 2020-12-20 15:03

can some one tell me how can i remove string element from an array i have google this and all i get is removing by index number

my example :

 var          


        
4条回答
  •  时光取名叫无心
    2020-12-20 15:34

    From https://stackoverflow.com/a/3955096/711129:

    Array.prototype.remove= function(){
        var what, a= arguments, L= a.length, ax;
        while(L && this.length){
            what= a[--L];
            while((ax= this.indexOf(what))!= -1){
                this.splice(ax, 1);
            }
        }
        return this;
    }
    var ary = ['three', 'seven', 'eleven'];
    
    ary.remove('seven')
    

    or, making it a global function:

    function removeA(arr){
    var what, a= arguments, L= a.length, ax;
    while(L> 1 && arr.length){
        what= a[--L];
        while((ax= arr.indexOf(what))!= -1){
            arr.splice(ax, 1);
        }
    }
    return arr;
    }
    var ary= ['three','seven','eleven'];
    removeA(ary,'seven')
    

    You have to make a function yourself. You can either loop over the array and remove the element from there, or have this function do it for you. Either way, it is not a standard JS feature.

提交回复
热议问题