如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
这个呢(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"]
其他回答
要从数组中删除未定义的元素,只需使用
常量数组=[{name:“tim”,年龄:1},未定义,{姓名:“ewrfer”,年龄:22岁},{姓名:“3tf5gh”,年龄:56},无效的{姓名:“kygm”,年龄:19岁},未定义,];console.log(array.filter(布尔));
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.filter可以在所有浏览器上运行。见下文。
var array = ["","one",0,"",null,0,1,2,4,"two"];
function isempty(x){
if(x!=="")
return true;
}
var res = array.filter(isempty);
document.writeln(res.toJSONString());
// gives: ["one",0,null,0,1,2,4,"two"]
这是您需要为IE添加的代码,但过滤器和函数式编程是值得的。
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
我只是在上面的“用全局构造函数调用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]
var a = [{a1: 1, children: [{a1: 2}, undefined, {a1: 3}]}, undefined, {a1: 5}, undefined, {a1: 6}]
function removeNilItemInArray(arr) {
if (!arr || !arr.length) return;
for (let i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i , 1);
continue;
}
removeNilItemInArray(arr[i].children);
}
}
var b = a;
removeNilItemInArray(a);
// Always keep this memory zone
console.log(b);