ES6的過濾器方法:filter()

filter() 方法創(chuàng)建一個新數(shù)組, 其包含通過所提供函數(shù)實(shí)現(xiàn)的測試的所有元素。

var arr = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

constnewArr = arr.filter(arrItem => word.length > 6);

console.log(newArr); //["exuberant", "destruction", "present"]

  • 語法
var newArray = arr.filter(
  callback(element[, index[, array]])[, thisArg]
)
  • 參數(shù)

    • callback:回調(diào)函數(shù)
    • element:arr數(shù)組中正在被處理的數(shù)據(jù)
    • index:element的下標(biāo),可選
    • array:調(diào)用了 filter 的數(shù)組本身,可選
    • thisArg:執(zhí)行 callback 時,用于 this 的值,可選
  • 返回值
    一個新的、由通過測試的元素組成的數(shù)組,如果沒有任何數(shù)組元素通過測試,則返回空數(shù)組。

  • 描述
    filter 為數(shù)組中的每個元素調(diào)用一次 callback 函數(shù),并利用所有使得 callback 返回 true 或等價于 true 的值的元素創(chuàng)建一個新數(shù)組。callback 只會在已經(jīng)賦值的索引上被調(diào)用,對于那些已經(jīng)被刪除或者從未被賦值的索引不會被調(diào)用。那些沒有通過 callback 測試的元素會被跳過,不會被包含在新數(shù)組中。
    callback 被調(diào)用時傳入三個參數(shù): 元素的值、元素的索引、被遍歷的數(shù)組本身
    如果為 filter 提供一個 thisArg 參數(shù),則它會被作為 callback 被調(diào)用時的 this 值。否則,callbackthis 值在非嚴(yán)格模式下將是全局對象,嚴(yán)格模式下為 undefinedcallback 函數(shù)最終觀察到的 this 值是根據(jù)通常函數(shù)所看到的 "this"的規(guī)則確定的。
    filter 不會改變原數(shù)組,它返回過濾后的新數(shù)組。
    filter 遍歷的元素范圍在第一次調(diào)用 callback 之前就已經(jīng)確定了。在調(diào)用 filter 之后被添加到數(shù)組中的元素不會被 filter 遍歷到。如果已經(jīng)存在的元素被改變了,則他們傳入 callback 的值是 filter 遍歷到它們那一刻的值。被刪除或從來未被賦值的元素不會被遍歷到。

  • 例子
    過濾 JSON 中的無效條目
    以下示例使用 filter() 創(chuàng)建具有非零 id 的元素的 json。

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];

var invalidEntries = 0;

function isNumber(obj) {
  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}

function filterByID(item) {
  if (isNumber(item.id) && item.id !== 0) {
    return true;
  } 
  invalidEntries++;
  return false; 
}

var arrByID = arr.filter(filterByID);

console.log('Filtered Array\n', arrByID); 
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]

console.log('Number of Invalid Entries = ', invalidEntries); 
// Number of Invalid Entries = 5

在數(shù)組中搜索
下例使用 filter() 根據(jù)搜索條件來過濾數(shù)組內(nèi)容。

var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
function filterItems(query) {
  return fruits.filter(function(el) {
      //toLowerCase:字符串字母小寫
      //indexOf:某個指定的字符串值在字符串中首次出現(xiàn)的位置。
      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
  })
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
  • Polyfill
    filter 被添加到 ECMA-262 標(biāo)準(zhǔn)第 5 版中,因此在某些實(shí)現(xiàn)環(huán)境中不被支持??梢园严旅娴拇a插入到腳本的開頭來解決此問題,該代碼允許在那些沒有原生支持 filter 的實(shí)現(xiàn)環(huán)境中使用它。該算法是 ECMA-262 第 5 版中指定的算法,假定 fn.call 等價于 Function.prototype.call 的初始值,且 Array.prototype.push 擁有它的初始值。
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,
        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;
  };
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容