JavaScript ES6 Array.filter()方法總結

本篇文章參考以下博文

一、定義

   filter() 方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。

   filter 的中文意思是“篩選”,顧名思義,會對數組中的元素挨個進行檢查,檢查通過的,才能組成新的數組。

二、語法

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
  • callback
    用來測試數組的每個元素的函數。返回 true 表示該元素通過測試,保留該元素,false 則不保留。它接受以下三個參數:
    • element
      數組中當前正在處理的元素。
    • index 可選
      正在處理的元素在數組中的索引。
    • array 可選
      調用了 filter 的數組本身。
  • thisArg 可選
    執行 callback 時,用於 this 的值。

三、實例

3.1 過濾數組中的假值

let array= [false, null, undefined, NaN, 0, ""]
array.filter(Boolean)  // []

3.2 數組中不同的部分

let arr1 = [1, 2, 3, 4], arr2 = [3, 4, 5];
let arr= [...arr1, ...arr2].filter(item => !arr1.includes(item) || !arr2.includes(item)) //[1, 2, 5]

3.3 數組去重

let arr = ['name','age','friends','height','weight','name','age']
let newArr = arr.filter((v, index)=> {
    return arr.indexOf(v) === index // 該元素第一次在數組中出現的位置是否等於當前索引值
})

四、轉化爲 ES5 之後的源碼

if (!Array.prototype.filter){
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
        throw new TypeError();
   
    var len = this.length >>> 0, // 這一步是保證 this.length 爲正整數
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;
    if (thisArg === undefined){
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func(t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }
    else{
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func.call(thisArg, t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }
   
    res.length = c; // shrink down array to proper size
    return res;
  };
}

  上面代碼中 >>> 0 是爲了保證 this.length 爲正整數,具體解釋戳 這裏




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