如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
要从数组中删除未定义的元素,只需使用
常量数组=[{name:“tim”,年龄:1},未定义,{姓名:“ewrfer”,年龄:22岁},{姓名:“3tf5gh”,年龄:56},无效的{姓名:“kygm”,年龄:19岁},未定义,];console.log(array.filter(布尔));
其他回答
要从数组中删除未定义的元素,只需使用
常量数组=[{name:“tim”,年龄:1},未定义,{姓名:“ewrfer”,年龄:22岁},{姓名:“3tf5gh”,年龄:56},无效的{姓名:“kygm”,年龄:19岁},未定义,];console.log(array.filter(布尔));
由于没有其他人提到它,而且大多数人的项目中都包含下划线,因此您也可以使用_.without(array,*values);。
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
“误用”。。。在(对象成员)循环中。=>循环体中仅显示真实值。
// --- 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);
这个呢(ES6):从数组中删除Falsy值。
var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];
arr.filter((v) => (!!(v)==true));
//output:
//[1, 2, "test", "false", true, 3, 4, 5, "end"]
如果使用库是一个选项,我知道underscore.js有一个名为compact()的函数http://documentcloud.github.com/underscore/它还有其他几个与数组和集合相关的有用函数。
以下是他们文档的摘录:
_.compact(数组)返回删除了所有错误值的数组副本。在JavaScript中,false、null、0、“”、undefined和NaN都是假的。_.compact([0,1,false,2,'',3]);=> [1, 2, 3]