重写数组遍历方法(forEach,filter,map,reduce)

直接上代码了

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

Array.prototype.myForEach = function (callback) {
let arg2 = arguments[1] || window;
for (let i = 0; i < this.length; i++) {
callback.apply(arg2, [this[i], i, this]);
}
};

Array.prototype.myMap = function (callback) {
let arg2 = arguments[1] || window;
let newArr = [];
for (let i = 0; i < this.length; i++) {
// 这里需要对对象进行深拷贝,这里就省略了
newArr.push(callback.apply(arg2, [this[i], i, this]));
}
return newArr;
};

Array.prototype.myFilter = function (callback) {
let arg2 = arguments[1] || window;
let newArr = [];
for (let i = 0; i < this.length; i++) {
// 这里需要对对象进行深拷贝,这里就省略了
callback.apply(arg2, [this[i], i, this]) ? newArr.push(this[i]) : newArr;
}
return newArr;
};

Array.prototype.myEvery = function (callback) {
let arg2 = arguments[1] || window;
let gate = true;
for (let i = 0; i < this.length; i++) {
if (!callback.apply(arg2, [this[i], i, this])) {
gate = false;
break;
}
}
return gate;
};

Array.prototype.mySome = function (callback) {
let arg2 = arguments[1] || window;
let gate = false;
for (let i = 0; i < this.length; i++) {
if (callback.apply(arg2, [this[i], i, this])) {
gate = true;
break;
}
}
return gate;
};

Array.prototype.myReduce = function (callback, initialValue) {
for (let i = 0; i < this.length; i++) {
// 这里需要对对象进行深拷贝,这里就省略了
initialValue = callback(initialValue, this[i], i, this);
}
return initialValue;
};

Array.prototype.myReduceRight = function (callback, initialValue) {
for (let i = this.length - 1; i >= 0; i--) {
// 这里需要对对象进行深拷贝,这里就省略了
initialValue = callback(initialValue, this[i], i, this);
}
return initialValue;
};