如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
实际上,您可以使用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));
其他回答
如果您有Javascript 1.6或更高版本,您可以使用Array.filter,使用简单的return true回调函数,例如:
arr = arr.filter(function() { return true; });
因为.filter会自动跳过原始数组中缺少的元素。
上面链接的MDN页面还包含一个很好的错误检查版本的过滤器,可以在不支持官方版本的JavaScript解释器中使用。
注意,这不会删除空条目,也不会删除具有显式未定义值的条目,但OP特别请求“缺少”条目。
那怎么办
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
带下划线/Loddash:
一般使用情况:
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
有空:
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
无需参阅lodash文档。
这可能会帮助您: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));
});
};
使用正则表达式筛选出无效条目
array = array.filter(/\w/);
filter + regexp