js手写filter方法

直接上干货

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Array.prototype.myFilter = function (callback, thisArg) {
if (this == null) {
throw new TypeError("this is null or not defined");
}

if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}

const res = [];

// 让O成为回调函数的对象传递(强制转换对象)

const O = Object(this);

// >>>0 保证len为number,且为正整数

const len = O.length >>> 0;

for (let i = 0; i < len; i++) {
// 检查i是否在O的属性(会检查原型链)

if (i in O) {
// 回调函数调用传参

if (callback.call(thisArg, O[i], i, O)) {
res.push(O[i]);
}
}
}

return res;
};

// 使用示例

let arr = [1, 2, 3, 4, 5];

let newArr = arr.myFilter(function (item) {
return item > 3;
});

console.log(newArr); // 输出:[4, 5]

js手写filter方法
https://blog.funfe.cn/2023/11/29/20231129151306/
作者
李鹏杰
发布于
2023年11月29日
许可协议