如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
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)
其他回答
使用正则表达式筛选出无效条目
array = array.filter(/\w/);
filter + regexp
美好的很不错的我们也可以像这样替换所有数组值
Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
for( var i = 0; i < this.length; i++ )
{
if( this[i] == OldValue )
{
this[i] = newValue;
}
}
};
您可能会发现,循环遍历数组并使用要从数组中保留的项构建新数组比按照建议进行循环和拼接更容易,因为在循环遍历时修改数组的长度可能会带来问题。
你可以这样做:
function removeFalsyElementsFromArray(someArray) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(someArray[index]) {
newArray.push(someArray[index]);
}
}
return newArray;
}
实际上,这里有一个更通用的解决方案:
function removeElementsFromArray(someArray, filter) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(filter(someArray[index]) == false) {
newArray.push(someArray[index]);
}
}
return newArray;
}
// then provide one or more filter functions that will
// filter out the elements based on some condition:
function isNullOrUndefined(item) {
return (item == null || typeof(item) == "undefined");
}
// then call the function like this:
var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
var results = removeElementsFromArray(myArray, isNullOrUndefined);
// results == [1,2,3,3,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)
试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误
function removeEmptyElem(ary) {
for (var i = ary.length - 1; i >= 0; i--) {
if (ary[i] == undefined) {
ary.splice(i, 1);
}
}
return ary;
}