Definition and usage
The filter() method creates a new array whose elements are checked by checking all elements in the specified array that meet the criteria.
Note: filter() does not check for empty arrays.
Note: filter() does not alter the original array
The filter() function is a higher-order function used to filter some elements and then return some elements
Let's not talk much, just go to the code
// filter函数的参数
let arr = ['a', 'b', 'c']
let array = arr.filter((item, index, self) => {
console.log(item, index, self)
})
//依次返回 a 0 (3) ["a", "b", "c"] b 1 (3) ["a", "b", "c"] c 2 (3) ["a", "b", "c"]
//即第⼀个参数是⾥⾯的元素,第⼆个参数为元素索引值,第三个参数为数组本⾝
// 1.⽤filter筛选出数组⾥所有偶数
let arr1 = [1, 2, 3, 4, 5, 6]
let arr2 = arr1.filter(item => {
return item % 2 == 0
})
console.log(arr2) // [2, 4, 6]
// 3.filter数组去重
let arr5 = ['11', 'aaa', 'bb', 'aaa', 'bb']
let arr6 = []
arr6 = arr5.filter((item, index, self) => {
return self.indexOf(item) === index
})
console.log(arr6) // ["11", "aaa", "bb"]
// 4.过滤掉数组⾥的⼩值:
let arr7 = [1, 2, 3, 4, 5, 7, 60]
let arr8 = arr7.filter((item) => {
return item >= 4
})
console.log(arr8) //[4, 5, 7, 60]
example:
var properties =[
'1','2','3','4','undefined','undefined',undefined,null
]
// let aa = properties.filter((item,index) => {
// if( item != 'undefined' && item != null && item != undefined){
// return item
// }
// })
let aa = properties.filter(item => item != 'undefined' && item != null && item != undefined)