javascript filter詳解及應用

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實現去重
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]

filter+indexof

**利用filter的過濾功能和indexof返回數組項所在的索引,相同項返回第一個的索引這個特性。

您的點贊是我繼續寫下去的動力!

歡迎吐槽! 謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章