方式一:
比较简单的方式使用filter
方法,同样可以过滤undefined
,当需要过滤空格时候使用.trim()
方法
let arr1 = [1, 2, 3, 4, 5, null, 6, undefined]
let arr2 = ["1", "2", "3", null, "4", undefined, "5", " ", "7"]
let newArr = arr1.filter(item => item)
let newArrTrim = arr2.filter((it) => {
return it && it.trim();
})
console.log(newArr) // [ 1, 2, 3, 4, 5, 6 ]
console.log(newArrTrim) // [ '1', '2', '3', '4', '5', '7' ]
方式二:
使用遍历的方式进行逐个判断进行数组数据的修改
let arr = ["1", "2", "3", null, "4", undefined, "5", " ", "7"]
for (let i = 0; i < arr.length; i++){
if (arr[i] === " " || arr[i] === null || typeof (arr[i]) === "undefined") {
arr.splice(i, 1)
i--;
}
}
console.log(arr) // [ '1', '2', '3', '4', '5', '7' ]
个人博客已上线,欢迎来访~
传送门:夜雨炊烟