如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
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)
其他回答
如果使用库是一个选项,我知道underscore.js有一个名为compact()的函数http://documentcloud.github.com/underscore/它还有其他几个与数组和集合相关的有用函数。
以下是他们文档的摘录:
_.compact(数组)返回删除了所有错误值的数组副本。在JavaScript中,false、null、0、“”、undefined和NaN都是假的。_.compact([0,1,false,2,'',3]);=> [1, 2, 3]
以上答案都不适用于所有类型。下面的解决方案将删除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))
这可能会帮助您:https://lodash.com/docs/4.17.4#remove
var details = [
{
reference: 'ref-1',
description: 'desc-1',
price: 1
}, {
reference: '',
description: '',
price: ''
}, {
reference: 'ref-2',
description: 'desc-2',
price: 200
}, {
reference: 'ref-3',
description: 'desc-3',
price: 3
}, {
reference: '',
description: '',
price: ''
}
];
scope.removeEmptyDetails(details);
expect(details.length).toEqual(3);
scope.removeEmptyDetails = function(details){
_.remove(details, function(detail){
return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
});
};
试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误
function removeEmptyElem(ary) {
for (var i = ary.length - 1; i >= 0; i--) {
if (ary[i] == undefined) {
ary.splice(i, 1);
}
}
return ary;
}
这是可行的,我在AppJet中测试了它(你可以复制粘贴代码到它的IDE上,然后按“reload”查看它的工作情况,不需要创建帐户)
/* appjet:version 0.1 */
function Joes_remove(someArray) {
var newArray = [];
var element;
for( element in someArray){
if(someArray[element]!=undefined ) {
newArray.push(someArray[element]);
}
}
return newArray;
}
var myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
print("Original array:", myArray2);
print("Clenased array:", Joes_remove(myArray2) );
/*
Returns: [1,2,3,3,0,4,4,5,6]
*/