一、对reduce的理解(聚合)
reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其简化为单个值。
reduce 接收两个参数:
第一个参数是在每一项上调用的函数
该函数接收 4 个参数:
前一个值 prev
当前值 cur
项的索引 index
数组对象 array
第二个可选参数是作为归并基础的初始值
reduce 方法返回一个最终的值。
实现的过程
- 不断地对数组的前两项“取出”,对其执行目标函数,计算得到的返回值
- 把上述返回值“填回”数组首部,作为新的 array[0]
- 持续循环执行这个过程,直到数组中每一项都访问了一次
- 返回最终结果
二、实现reduce
(1)递归实现
const funreduce = (f,acc,arr)=>{
if(arr.length === 0){
return acc
}
const [head,...tail] = arr
return funreduce(f,f(acc,head),tail)
}
array.prototype.myreduce = function(fn,initvalue){
const array = this
return myreduce(fn,initvalue,array)
}
// 第二版
Array.prototype.fakeReduce = function fakeReduce(fn, base) {
let initialArr = this;
let arr = initialArr.concat();
if (base) arr.unshift(base);
let index, newValue;
while (arr.length > 1) {
index = initialArr.length - arr.length + 1;
newValue = fn.call(null, arr[0], arr[1], index, initialArr);
arr.splice(0, 2, newValue); // 直接用 splice 实现替换
}
return newValue;
};
//重构非递归
Array.prototype.myReduce = function (cb, initialValue) {
const array = this
let acc = initialValue || array[0]
const startIndex = initialValue ? 0 : 1
for (let i = startIndex; i < array.length; i++) {
const cur = array[i]
acc = cb(acc, cur, i, array)
}
return acc
}