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


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方法


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM