如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
以上答案都不适用于所有类型。下面的解决方案将删除null、undefined、{}[]、NaN,并保留日期字符串,最好的是它甚至从嵌套对象中删除。
function removeNil(obj) {
// recursively remove null and undefined from nested object too.
return JSON.parse(JSON.stringify(obj), (k,v) => {
if(v === null || v === '') return undefined;
// convert date string to date.
if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))
return new Date(v);
// remove empty array and object.
if(typeof v === 'object' && !Object.keys(v).length) return undefined;
return v;
});
}
函数removeNil(obj){//递归地从嵌套对象中删除null和undefined。返回JSON.parse(JSON.stringify(obj),(k,v)=>{如果(v===null||v==='')返回undefined;//将日期字符串转换为日期。if(typeof v==“string”&&/^\d\d\d\d-\d\dT\dd:\d\d:\d\d.d.d\dZ$/.test(v))返回新日期(v);//删除空数组和对象。if(typeof v=='object'&&!object.keys(v).length)返回undefined;返回v;});}常量ob={s: “a”,b: 43中,国家:['a','b','c'],l: 空,n: {ks:“a”,efe:null,ce:“”},d: new Date(),nan:nan,k: 未定义,emptyO:{},emptyArr:[],}常量输出=removeNil(ob);console.log(输出);console.log('测试:',ob.countries.length,typeof(ob.d))
其他回答
@阿尔尼塔克
实际上,如果您添加一些额外的代码,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;
};
}
ES6:
let newArr = arr.filter(e => e);
只需一个衬垫:
[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]
这个呢(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"]
实际上,您可以使用ES6+方法,假设数组如下:
const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
答案可以是以下两种方式之一:
第一种方式:常量clearArray=arr.filter(i=>i);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]第二种方式:const clearArray=arr.filter(布尔值);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
2022年10月14日更新:
这两个答案并不完全正确,即使在给定的例子中,是的,它是有效的,但请注意给定数组中的数字0,通过这两种方式,数字0都会消失,这显然与使用布尔强制检查项目有关。
完全正确的方法是检查nulish并删除它们:
const notNil = (i) => !(typeof i === 'undefined' || i === null);
const clearArray = arr.filter(i => isNil(i));
常量arr=[1,2,3,未定义,4,5,6,未定义、7,8,未定义;未定义,0,9];常量notNil=(i)=>!(类型i===“未定义”||i===null);console.log(“非nil:”,arr.filter(非nil));