JavaScript中为了从数组中删除空元素,可以使用filter()方法。filter()方法将返回一个新数组,其中包含传递回调函数条件的元素。
array.filter()方法从给定数组中创建一个新数组,该数组由所提供数组中满足参数函数条件的元素组成。array.filter( function(cValue, index, arr), tValue )
参数:filter()方法接受下面列出的两个参数
function:它包含三个参数
cValue:此参数是必需的,它是当前元素的值。
index:该参数是可选的,它是当前元素的数组索引。
arr:此参数是可选的,它是当前元素所属的数组对象。
tValue:此参数是可选的,该值将传递给函数以用作其“this”值。如果为空,则将传递值“undefined”。
示例:从数组中删除undefined,null和empty元素html>
var array = ["a", "b", null, "c",
"", "d", undefined, "e", , , , , ,
"f", , 4, , 5, , 6, , , ,
];
var p_up = document.getElementById("up");
p_up.innerHTML = "原数组:" + array;
var p_down = document.getElementById("down");
var filtered = array.filter(function(el) {
return el != null;
});
p_down.innerHTML = "去除空元素的数组:" + filtered;
示例2:html>
var array = ["a", "b", null, "c",
"", "d", undefined, "e", , , , , ,
"f", , 4, , 5, , 6, , , ,
];
var p_up = document.getElementById("up");
p_up.innerHTML = "原数组:" + array;
var p_down = document.getElementById("down");
var filtered = array.filter(function(el) {
return el;
});
p_down.innerHTML = "去除空元素的数组:" + filtered;