如何在JavaScript中删除数组中的空元素?

是否有一种简单的方法,或者我需要循环并手动删除它们?


当前回答

只需一个衬垫:

[1, false, "", undefined, 2].filter(Boolean); // [1, 2]

或使用underscorejs.org:

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]

其他回答

使用筛选器删除数组中的空字符串。

var s=['1201,karthikeyan,K201,直升机,karthikeyan.a@limitlessmobil.com,8248606269,7/14/201745680,TN-KAR24,88001000200300,Karthikeyan,2017年11月24日,Karthikey an,2017月11日,可用\r,'' ]var newArr=s.filter(函数(条目){return entry.trim()!=“”;})console.log(newArr);

使用正则表达式筛选出无效条目

array = array.filter(/\w/);
filter + regexp
// recursive implementation
function compact(arr) {
        const compactArray = [];
        //base case 
        if(!arr.length) return []
        if(typeof arr[0] !== "undefined" 
          && arr[0]!==null && arr[0] !== " " && 
          arr[0]!== false &&
          arr[0]!== 0){
          compactArray.push(arr[0]);
        }
        return compactArray.concat(compact(arr.slice(1)))
    }
    
    compact([1,0,false,null,undefined,"banana"])`

@阿尔尼塔克

实际上,如果您添加一些额外的代码,Array.filter可以在所有浏览器上运行。见下文。

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"]  

这是您需要为IE添加的代码,但过滤器和函数式编程是值得的。

//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;
  };
}
var data= { 
    myAction: function(array){
        return array.filter(function(el){
           return (el !== (undefined || null || ''));
        }).join(" ");
    }
}; 
var string = data.myAction(["I", "am","", "working", "", "on","", "nodejs", "" ]);
console.log(string);

输出:

我正在研究nodejs

它将从数组中删除空元素并显示其他元素。