如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
您应该使用filter获取不含空元素的数组。ES6示例
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
其他回答
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
它将从数组中删除空元素并显示其他元素。
“误用”。。。在(对象成员)循环中。=>循环体中仅显示真实值。
// --- 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);
您可能会发现,循环遍历数组并使用要从数组中保留的项构建新数组比按照建议进行循环和拼接更容易,因为在循环遍历时修改数组的长度可能会带来问题。
你可以这样做:
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]
你明白了——你可以有其他类型的过滤函数。可能比你需要的更多,但我感觉很慷慨…;)
您应该使用filter获取不含空元素的数组。ES6示例
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
最简单的方法
[NaN,未定义,空,0,1,2,2000,无限].filter(布尔)