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值。否則,callback的this值在非嚴(yán)格模式下將是全局對象,嚴(yán)格模式下為undefined。callback函數(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;
};
}