How to remove specific element in array in javascript

This question already has an answer here:

  • How do I remove a particular element from an array in JavaScript? 62 answers

  • var newArray = [];
    var a=["a","b","c"];
    for(var i=0;i<a.length;i++)
        if(a[i]!=="a") newArray.push(a[i]);
    

    remove = function(ary, elem) {
        var i = ary.indexOf(elem);
        if (i >= 0) ary.splice(i, 1);
        return ary;
    }
    

    provided your target browser suppports array.indexOf , otherwise use the fallback code on that page.

    If you need to remove all equal elements, use filter as Rocket suggested:

    removeAll = function(ary, elem) {
        return ary.filter(function(e) { return e != elem });
    }
    

    如果您使用的是现代浏览器,则可以使用.filter

    Array.prototype.remove = function(x){
        return this.filter(function(v){
            return v !== x;
        });
    };
    
    var a = ["a","b","c"];
    var b = a.remove('a');
    
    链接地址: http://www.djcxy.com/p/3206.html

    上一篇: 从关联数组中删除值

    下一篇: 如何在javascript中删除数组中的特定元素