JS中去除数组中的假值(0, 空,undefined, null, false)

时间:2020-03-31 14:27:06   收藏:0   阅读:382

1.Array.filter()

arr.filter(Boolean)

2.也可以通过遍历判断数组, 空字符,undefined, null, false , 0转化为布尔类型都是 false;

let arr=[1, , null, false, undefined, 3]
let newArr= []
//法1
arr.forEach(item => {
if (item) {
newArr.push(item)
}
})
//法2
for (let item of arr) {
if (item) {
newArr.push(item)
}
}
3.第三方库方法

如 Lodash 库 compact方法

原文:https://www.cnblogs.com/zhulinxianxain/p/12604739.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!