# 1. Array.prototype.reduce()
# 1.1 描述
reduce() 方法对数组中的每个元素按序执行一个由您提供的reducer函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
回调函数第一次执行时,previousValue 和 currentValue 的取值有两种情况:
- 如果调用
reduce()时提供了initialValue,previousValue取值则为initialValue,currentValue 则取数组中的第一个值。 - 如果没有提供
initialValue,那么previousValue取数组中的第一个值,currentValue取数组中的第二个值。
reducer 逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果是当前元素之前所有元素的总和)——直到没有更多的元素被相加。
详见:Array.prototype.reduce() (opens new window)
# 1.2
// 1. 首先让数组的原型上有reduceTo方法
// 2. reduceTo的第一个参数类型为function,第二个参数为初始值
// 3. 要判断reduceTo有无初始值传入,如果有,fn回调函数的prev的值就为初始值,cur为数组里的第1个元素,下标从0开始;如果没有,prev的值为数组的第一个元素,cur为数组的第二个元素,下标从1开始。
Array.prototype.reduceTo = function(fn, initValue) {
if (!Array.isArray(this) || !this.length || typeof fn !== "function") {
return [];
} else {
let isInitValue = 0;
if (initValue) {
isInitValue = initValue;
}
let value = isInitValue ? isInitValue : this[0];
for (let index = isInitValue ? 0 : 1; index < this.length; index++) {
const element = this[index];
value = fn(value, element, index, this);
}
return value;
}
};
let arr = [3, 6, 7, 11, 5];
let res = arr.reduceTo((pre, cur, i, arr) => {
console.log(pre, cur, i, arr);
return pre + cur;
});
console.log("res", res);
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
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