摘抄與:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
概述
filter() 方法使用指定的函數測試所有元素,並創建一個包含所有通過測試的元素的新數組。
語法
var new_arrary = arr.filter(callback[, thisArg])
參數
-
callback:用來測試數組的每個元素的函數。調用時使用參數 (element, index, array)。返回true表示保留該元素(通過測試),false則不保留。 -
thisArg:可選。執行callback時的用於this的值。
描述
filter 為數組中的每個元素調用一次 callback 函數,並利用所有使得 callback 返回 true 或 等價於 true 的值 的元素創建一個新數組。callback 只會在已經賦值的索引上被調用,對於那些已經被刪除或者從未被賦值的索引不會被調用。那些沒有通過 callback 測試的元素會被跳過,不會被包含在新數組中。
callback 被調用時傳入三個參數:
- 元素的值
- 元素的索引
- 被遍歷的數組
如果為 filter 提供一個 thisArg 參數,則它會被作為 callback 被調用時的 this 值。否則,callback 的 this 值在非嚴格模式下將是全局對象,嚴格模式下為 undefined。
The thisvalue ultimately observable by callback is determined according to the usual rules for determining thethis seen by a function.
filter 不會改變原數組。
filter 遍歷的元素范圍在第一次調用 callback 之前就已經確定了。在調用 filter 之后被添加到數組中的元素不會被 filter 遍歷到。如果已經存在的元素被改變了,則他們傳入 callback 的值是 filter 遍歷到它們那一刻的值。被刪除或從來未被賦值的元素不會被遍歷到。
示例
例子:篩選排除掉所有的小值
下例使用 filter 創建了一個新數組,該數組的元素由原數組中值大於 10 的元素組成。
function isBigEnough(element) { return element >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]
兼容舊環境(Polyfill)
filter 被添加到 ECMA-262 標准第 5 版中,因此在某些實現環境中不被支持。可以把下面的代碼插入到腳本的開頭來解決此問題,該代碼允許在那些沒有原生支持 filter 的實現環境中使用它。該算法是 ECMA-262 第 5 版中指定的算法,假定 fn.call 等價於 的初始值,且 Function.prototype.call 擁有它的初始值。Array.prototype.push
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) Array.prototype.filter |
Standard | Initial definition. Implemented in JavaScript 1.6 |
| ECMAScript 2015 (6th Edition, ECMA-262) Array.prototype.filter |
Standard |
