filter
基本语法
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
- 参数
- callback 回调函数 true 是返回元素 false 过滤掉次元素
- element 当前正在处理的函数
- index 当前正在处理的函数的索引值
- array 调用 filter 函数的数组
- thisArg
- 执行 callback 时,用于 this 的值。
- 只有下面 this 的值是 undecided,其余 this 的值是 Window
"use strict";
let num = [0, 1, 2, 3, 4];
const res = num.filter(function (value) {
console.log(this);//打印的值为undecided
return value > 2;
});
-
filter 不会改变原数组,它返回过滤后的新数组,需要一个新的数组来接受结果
-
实现原理剖析
function myfilter(arr, callback) {
let newArr = [];
for (const value of arr) {
if (callback(value) === true) newArr.push(value);
}
return newArr;
}
console.log(
myfilter(num, function (item) {
return item > 2;
})
);
原理解释
- 需要传入一个数组和一个回调函数作为参数
- 创建一个新的数组来接受结果
- 通过回调函数的判断结果 将符合的数据压入新的数组
- 最后返回新的数组
实例
let num = [0, 1, 2, 3, 4];
const res = num.filter((value) => value > 2);
console.log(res); // {3,4}
补充
filter 被添加到 ECMA-262 标准第 5 版中,因此在某些实现环境中不被支持。可以把下面的代码插入到脚本的开头来解决此问题,该代码允许在那些没有原生支持 filter 的实现环境中使用它。该算法是 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;
};
}