如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
可以使用带有索引和in运算符的筛选器
设a=[1,,2,,,3];设b=a.filter((x,i)=>a中的i);console.log({a,b});
其他回答
“误用”。。。在(对象成员)循环中。=>循环体中仅显示真实值。
// --- 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"]
可以使用带有索引和in运算符的筛选器
设a=[1,,2,,,3];设b=a.filter((x,i)=>a中的i);console.log({a,b});
那怎么办
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
只需一个衬垫:
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
或使用underscorejs.org:
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]