如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
带下划线/Loddash:
一般使用情况:
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
有空:
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
无需参阅lodash文档。
其他回答
这样做怎么样
// Removes all falsy values
arr = arr.filter(function(array_val) { // creates an anonymous filter func
var x = Boolean(array_val); // checks if val is null
return x == true; // returns val to array if not null
});
我需要完成同样的任务,并遇到了这个线程。我最终使用数组“join”使用“_”分隔符创建字符串,然后使用正则表达式:-
1. replace "__" or more with just one "_",
2. replace preceding "_" with nothing "" and similarly
3. replace and ending "_" with nothing ""
…然后使用数组“拆分”生成一个已清理的数组:-
var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
var myStr = "";
myStr = myArr.join("_");
myStr = myStr.replace(new RegExp(/__*/g),"_");
myStr = myStr.replace(new RegExp(/^_/i),"");
myStr = myStr.replace(new RegExp(/_$/i),"");
myArr = myStr.split("_");
alert("myArr=" + myArr.join(","));
…或1行代码:-
var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
myArr = myArr.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");
alert("myArr=" + myArr.join(","));
…或,扩展Array对象:-
Array.prototype.clean = function() {
return this.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");
};
var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
alert("myArr=" + myArr.clean().join(","));
ES6:
let newArr = arr.filter(e => e);
如果您有Javascript 1.6或更高版本,您可以使用Array.filter,使用简单的return true回调函数,例如:
arr = arr.filter(function() { return true; });
因为.filter会自动跳过原始数组中缺少的元素。
上面链接的MDN页面还包含一个很好的错误检查版本的过滤器,可以在不支持官方版本的JavaScript解释器中使用。
注意,这不会删除空条目,也不会删除具有显式未定义值的条目,但OP特别请求“缺少”条目。
第一个例子是,当使用上面投票最高的答案时,我得到的字符串长度大于1的单个字符。下面是我解决这个问题的方法。
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
如果未定义,则不返回,如果长度大于0,则返回。希望这能帮助一些人。
退换商品
["some string yay", "Other string yay"]