如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
使用正则表达式筛选出无效条目
array = array.filter(/\w/);
filter + regexp
其他回答
@阿尔尼塔克
实际上,如果您添加一些额外的代码,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;
};
}
就地解决方案:
function pack(arr) { // remove undefined values
let p = -1
for (let i = 0, len = arr.length; i < len; i++) {
if (arr[i] !== undefined) { if (p >= 0) { arr[p] = arr[i]; p++ } }
else if (p < 0) p = i
}
if (p >= 0) arr.length = p
return arr
}
let a = [1, 2, 3, undefined, undefined, 4, 5, undefined, null]
console.log(JSON.stringify(a))
pack(a)
console.log(JSON.stringify(a))
要移除孔,应使用
arr.filter(() => true)
arr.flat(0) // New in ES2019
对于删除孔、空和未定义:
arr.filter(x => x != null)
用于删除hole和falsy(null,undefined,0,-0,0n,NaN,“”,false,document.all)值:
arr.filter(x => x)
arr=[,null,(void 0),0,-0,0n,NaN,false,“”,42];console.log(arr.filter(()=>true));//[null,(void 0),0,-0,0n,NaN,false,“”,42]console.log(arr.filter(x=>x!=null));//[0,-0,0n,NaN,假,“”,42]console.log(arr.filter(x=>x));//[42]
注:
孔是一些没有元素的数组索引。
arr = [, ,];
console.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a hole
arr[42] = 42;
console.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole
arr1 = [1, 2, 3];
arr1[0] = (void 0);
console.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole
arr2 = [1, 2, 3];
delete arr2[0]; // NEVER do this please
console.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole
上述所有方法都返回给定数组的副本,而不是就地修改它。
arr = [1, 3, null, 4];
filtered = arr.filter(x => x != null);
console.log(filtered); // [1, 3, 4]
console.log(arr); // [1, 3, null, 4]; not modified
试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误
function removeEmptyElem(ary) {
for (var i = ary.length - 1; i >= 0; i--) {
if (ary[i] == undefined) {
ary.splice(i, 1);
}
}
return ary;
}
下面是一个使用变量行为和ES2015胖箭头表达式的示例:
Array.prototype.clean = function() {
var args = [].slice.call(arguments);
return this.filter(item => args.indexOf(item) === -1);
};
// Usage
var arr = ["", undefined, 3, "yes", undefined, undefined, ""];
arr.clean(undefined); // ["", 3, "yes", ""];
arr.clean(undefined, ""); // [3, "yes"];