如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
“误用”。。。在(对象成员)循环中。=>循环体中仅显示真实值。
// --- Example ----------
var field = [];
field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------
var originalLength;
// Store the length of the array.
originalLength = field.length;
for (var i in field) {
// Attach the truthy values upon the end of the array.
field.push(field[i]);
}
// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);
其他回答
我只是在上面的“用全局构造函数调用ES5的数组..filter()”高尔夫技巧中添加了我的声音,但我建议使用Object而不是上面建议的String、Boolean或Number。
具体来说,ES5的filter()已经不会为数组中未定义的元素触发;因此,一个普遍返回true(返回所有元素filter()命中)的函数必然只返回未定义的元素:
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
然而,写出。。。(function(){return true;})的长度大于写入。。。(对象);在任何情况下,Object构造函数的返回值都将是某种类型的对象。与上面建议的基本装箱构造函数不同,没有可能的对象值是假的,因此在布尔设置中,object是function(){return true}的缩写。
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
简单ES6
['a','b','',,,'w','b'].filter(v => v);
试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误
function removeEmptyElem(ary) {
for (var i = ary.length - 1; i >= 0; i--) {
if (ary[i] == undefined) {
ary.splice(i, 1);
}
}
return ary;
}
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
它将从数组中删除空元素并显示其他元素。
带下划线/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文档。