本篇文章参考以下博文
一、定义
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
filter 的中文意思是“筛选”,顾名思义,会对数组中的元素挨个进行检查,检查通过的,才能组成新的数组。
二、语法
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
- callback
用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:- element
数组中当前正在处理的元素。 - index 可选
正在处理的元素在数组中的索引。 - array 可选
调用了 filter 的数组本身。
- element
- thisArg 可选
执行 callback 时,用于 this 的值。
三、实例
3.1 过滤数组中的假值
let array= [false, null, undefined, NaN, 0, ""]
array.filter(Boolean) // []
3.2 数组中不同的部分
let arr1 = [1, 2, 3, 4], arr2 = [3, 4, 5];
let arr= [...arr1, ...arr2].filter(item => !arr1.includes(item) || !arr2.includes(item)) //[1, 2, 5]
3.3 数组去重
let arr = ['name','age','friends','height','weight','name','age']
let newArr = arr.filter((v, index)=> {
return arr.indexOf(v) === index // 该元素第一次在数组中出现的位置是否等于当前索引值
})
四、转化为 ES5 之后的源码
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, // 这一步是保证 this.length 为正整数
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;
};
}
上面代码中 >>> 0 是为了保证 this.length 为正整数,具体解释戳 这里