JS中去除数组中的无效值(空,undefined, null, false)

版权声明:原创的文章转载请注明出处,谢谢! https://blog.csdn.net/weixin_41804429/article/details/84623400

1.Array.filter()

arr.filter(item => item)

2.也可以通过遍历判断数组, 空字符,undefined, null, false 转化为布尔类型都是 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)
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_41804429/article/details/84623400
今日推荐