定義和用法
filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
注意: filter() 不會對空數組進行檢測。
注意: filter() 不會改變原始數組。
語法
array.filter(function(currentValue,index,arr), thisValue)
參數說明
參數 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必須。函數,數組中的每個元素都會執行這個函數 函數參數:
|
||||||||
thisValue | 可選。對象作為該執行回調時使用,傳遞給函數,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值為 "undefined" |
首先回顧一下filter的作用:過濾數組中符合條件的元素
基本用法
1 |
let arr = [1, 3, 5, 8] |
另外也可以用來過濾對象數組中符合條件的對象,eg:
1 |
let arrObj = [{ |
進階用法
數組去重(有點過時)
1 |
let arr = [1, 2, 3, 2, 3, 4] |
目前比較常用的方法是使用ES6的set完成,eg:
1 |
let arr = [1, 2, 3, 2, 3, 4] |
數組中的空字符去除
1 |
let arr = ['1', '2', '3', '', null, undefined, ' ', '4'] |
高級用法
結合map使用可以先過濾出符合條件的對象然后去除某些不需要的字段,比如:
1 |
// 需求: 年齡大於18的姓名 |
filter()
簡單講filter就是一個數組過濾器,參數接收一個函數,數組的每一項經過函數過濾,返回一個符合過濾條件的新數組
函數接收三個參數:
- item (當前遍歷的數組項)
- i (當前項索引)
- arr (調用filter數組本身)
// 需求找到數組內偶數
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let newArr = arr.filter((item, i, arr) => { //函數本身返回布爾值,只有當返回值為true時,當前項存入新數組。 return item % 2 == 0 }) console.log(newArr)
再來一個應用,巧妙地用filter結合indexof實現去重
indexOf在js中有着重要的作用,可以判斷一個元素是否在數組中存在,或者判斷一個字符是否在字符串中存在,如果存在返回該元素或字符第一次出現的位置的索引,不存在返回-1。
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7] let newArr = arr1.filter(function(item, i, self) { let a = self.indexOf(item) console.log(`item----${item},self.indexOf(item)---${a},i----${i}`) return self.indexOf(item) === i; }); console.log(newArr) //[1, 2, 3, 4, 5, 6, 7, 8]