Array.filter精简版源码
基本思路
- 函数中的 this 指向调用这个 api 的数组
- 创建一个数组 arr 存储原函数的值
- 创建一个空数组,存放 fn 处理完的数据(fn处理数据的逻辑是开发者写的)
- 遍历原数组,把原数组中的每一项都通过fn处理,如果处理后返回的是true则将数据添加到空数组中
- 返回处理后的数据
代码实现
Array.prototype._filter = function(fn){
if(typeof fn !== "function") return
// 创建一个数组 arr 存储原函数的值
const arr = this;
// 创建一个空数组,存放 fn 处理完的数据(fn处理数据的逻辑是开发者写的)
let newArr = [];
for(let i=0;i<arr.length;i++){
// 数组api中的回调函数与this无关,所以可以给fn的this指向null
let res = fn.call(null,arr[i],i,arr);
if(res === true){
newArr.push(arr[i])
}
}
// 返回处理后的数据
return newArr
}