【js學習】js中filter過濾用法總結
阿新 • • 發佈:2022-02-17
定義和用法
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]作者:gtea 部落格地址:https://www.cnblogs.com/gtea