MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Array.prototype.filter()

翻譯不完整。請協助 翻譯此英文文件

filter() 方法會建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

var longWords = words.filter(function(word){
  return word.length > 6;
})

// Filtered array longWords is ["exuberant", "destruction", "present"]

語法

var newArray = arr.filter(callback[, thisArg])

參數

callback
此函式為一個斷言,用於測試陣列中的每個元素。回傳值為 true 時將當前的元素保留至新陣列中,若為 false 則不保留。可傳入三個參數:
element
原陣列目前所迭代處理中的元素。
index
原陣列目前所迭代處理中的元素之索引。
array
呼叫 filter 方法的陣列。
thisArg 選擇性
選擇性的參數。執行 callback 回呼函式的 this 值。

回傳值

一個元素為通過回呼函式檢驗的新陣列。

描述

filter() 會將所有陣列中的元素分別傳入一次至 callback 函式當中,並將所有傳入此回呼函式並得到回傳值為 Truthy 的元素建構成一個新的陣列。callback 函式只會於陣列目前迭代之索引有指派值時被呼叫,回呼函式不會在該陣列索引已被刪除或從未被賦值時被調用。原始陣列中沒有通過 callback 檢驗的元素會被簡單的跳過,且不會被包含在新建立的陣列中。

callback 函式於被調用時會傳入三個參數:

  1. 元素值
  2. 元素之索引
  3. 被迭代的陣列物件

若有提供 thisArg 參數予 filter 方法,thisArg 將會被當作回呼函式的 this 值,否則 this 會是 undefinedcallback 的最終 this 值是依據函式的 this 規則來決定。

filter() 不會修改呼叫它的原始陣列。

filter() 方法所回傳之新陣列的範圍,於 callback 函式第一次被調用之前就已經被設定。而在呼叫 filter() 之後才加至原始陣列中的元素,將不會傳入 callback 當中。假如原始陣列中元素的值改變或被刪除了,則 callback 得到此元素的值將會是 filter() 傳入元素當下的值。而被刪除的原始陣列元素並不會被迭代到。

範例

過濾所有的小數字

以下範例會用 filter() 建立一個把所有小於 10 的元素都移掉的陣列。

function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

從 JSON 過濾無效的項目

以下範例會用 filter() 建立一個把非零 numeric 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)) {
    return true;
  } 
  invalidEntries++;
  return false; 
}

var arrByID = arr.filter(filterByID);

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

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

Searching in array

Following example uses filter() to filter array content based on search criteria

var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
 * Array filters items based on search criteria (query)
 */
function filterItems(query) {
  return fruits.filter(function(el) {
      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
  })
}

console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']

ES2015 Implementation

const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
 * Array filters items based on search criteria (query)
 */
function filterItems(query) {
  return fruits.filter((el) =>
    el.toLowerCase().indexOf(query.toLowerCase()) > -1
  )
}

console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']

Polyfill

filter() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that fn.call evaluates to the original value of Function.prototype.call(), and that Array.prototype.push() has its original value.

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

規範

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'Array.prototype.filter' in that specification.
Standard Initial definition. Implemented in JavaScript 1.6.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array.prototype.filter' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'Array.prototype.filter' in that specification.
Draft  

瀏覽器相容性

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 1.5 (1.8) 9 (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) 1.0 (1.8) (Yes) (Yes) (Yes)

參見

文件標籤與貢獻者

 此頁面的貢獻者: jackblackevo, jsgao0, iigmir, alk03073135
 最近更新: jackblackevo,