Remove empty elements from an array in Javascript

后端 未结 30 2632
无人共我
无人共我 2020-11-21 09:53

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

30条回答
  •  星月不相逢
    2020-11-21 10:43

    @Alnitak

    Actually Array.filter works on all browsers if you add some extra code. See below.

    var array = ["","one",0,"",null,0,1,2,4,"two"];
    
    function isempty(x){
    if(x!=="")
        return true;
    }
    var res = array.filter(isempty);
    document.writeln(res.toJSONString());
    // gives: ["one",0,null,0,1,2,4,"two"]  
    

    This is the code you need to add for IE, but filter and Functional programmingis worth is imo.

    //This prototype is provided by the Mozilla foundation and
    //is distributed under the MIT license.
    //http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
    
    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisp*/)
      {
        var len = this.length;
        if (typeof fun != "function")
          throw new TypeError();
    
        var res = new Array();
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
          if (i in this)
          {
            var val = this[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, this))
              res.push(val);
          }
        }
    
        return res;
      };
    }
    

提交回复
热议问题