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

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


当前回答

下面是一个使用变量行为和ES2015胖箭头表达式的示例:

Array.prototype.clean = function() {
  var args = [].slice.call(arguments);
  return this.filter(item => args.indexOf(item) === -1);
};

// Usage
var arr = ["", undefined, 3, "yes", undefined, undefined, ""];
arr.clean(undefined); // ["", 3, "yes", ""];
arr.clean(undefined, ""); // [3, "yes"];

其他回答

那怎么办

js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
foo = [0, 1, 2, "", , false, 3, "four", null]

foo.filter(e => e === 0 ? true : e)

回报

[0, 1, 2, 3, "four"]

如果你确定你的数组中没有0,那么它看起来会更好一些:

foo.filter(e => e)

由于没有其他人提到它,而且大多数人的项目中都包含下划线,因此您也可以使用_.without(array,*values);。

_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]

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

array = array.filter(/\w/);
filter + regexp

干净的方法。

var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]