1const arr = [1, 2, 3, 4];
2
3Array.prototype.MyReduce = function (callback, initialArray) {
4 let instance = this;
5 if (!callback) {
6 return initialArray;
7 }
8 const fn = function (res, index) {
9 if (index >= instance.length) {
10 return res;
11 }
12 const currentValue = instance[index];
13 return fn(callback(res, currentValue, index, instance), index + 1);
14 };
15 return fn(initialArray, 0);
16};
17
18const res = arr.MyReduce((result, currentValue, index, array) => {
19 return result + currentValue;
20}, 0);
21
22console.log("res", res);