reduce方法的实现

reduce方法的实现

reduce方法是一种归并数组的方法,它将从前往后遍历数组,并在所有数组元素的基础上构建一个返回值。reduce接收两个参数,第一个参数是对每个数组元素都会执行的回调函数,第二个参数是可选的初始值。

1 let array = [0, 1, 2, 3, 4];
2 array.reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue ); // 10

传递给reduce的回调函数接收四个参数:accumulator,currentValue,index,array。accumulator是累加器,如果reduce的第二个参数不存在,它将被初始化为数组的第一个元素,否则它将被初始化为reduce的第二个参数。之后,accumulator将保存每次调用回调函数所返回的结果,并在下一次调用回调函数时作为其参数。currentValue保存当前遍历的元素,index保存当前元素的索引,array表示被遍历的数组。在遍历完数组之后,reduce将返回accumulator的最终结果。

 1 // reduce方法的实现
 2 Array.prototype.myReduce = function (callBack, initialValue) {
 3     if (!((typeof callBack === "Function" || typeof callBack === "function") && this)) {
 4         throw new TypeError("The callback must be a function and the caller of reduce must not be null or undefined");
 5     }
 6 
 7     // 获取调用reduce方法的数组
 8     const array = Object(this);
 9 
10     // 获取数组长度
11     const len = array.length >>> 0;
12 
13     // 声明累加器,当前值和当前索引
14     let accumulator, currentValue, currentIndex;
15 
16     // 当数组为空且没有提供初始值时应该报错,此时执行reduce方法没有意义
17     if (!initialValue && len <= 0) {
18         throw new Error("Reduce of empty array with no initial value");
19     }
20 
21     if (initialValue) {
22         // 如果提供了初始值,则累加器被初始化为初始值
23         accumulator = initialValue;
24         for (let i = 0; i < len; i++) {
25             currentValue = array[i]; currentIndex = i;
26             accumulator = callBack(accumulator, currentValue, currentIndex, array);
27         }
28     } else {
29         // 如果没有提供初始值,则累加器被初始化为数组的第一个元素
30         accumulator = array[0];
31         for (let i = 1; i < len; i++) {
32             currentValue = array[i]; currentIndex = i;
33             accumulator = callBack(accumulator, currentValue, currentIndex, array);
34         }
35     }
36 
37     return accumulator;
38 }
posted @ 2021-04-30 16:21  曹冲字仓舒  阅读(497)  评论(0)    收藏  举报