之前对累加器使用的不多,总是对其充满一种神秘感觉。看完实现原理,仿佛觉得累加器不过如此了。现在回过头看看,重要的还是我们传入的逻辑处理函数fn。
简述:
- fn,函数作为参数传入,fn为我们定义的处理逻辑,传入内部待调用
- 内部维护两个变量,total 执行fn的结果,index 索引值
- 当index小于数组长度,持续执行fn函数(数组为this,因为是数组调用的reduce方法)
- fn接收参数,total,当前值this[index++],索引值index,数组this
- 将结果赋值给reduce,实现累加功能
- 循环完毕,将最终结果返回
Array.prototype.ireduce = function (fn, baseNumber) {
// 不能用箭头函数,否则没有this
if (Object.prototype.toString.call(this) !== '[object Array]') {
throw new TypeError('not an array');
}
if (typeof fn !== 'function') {
throw new Error(`${fn} is not a function`);
}
if (!this.length) {
throw new Error('reduce an empty array with no initial value');
}
// 维护两个变量:总计,索引值
// total
let total = baseNumber || 0;
// index
let index = 0;
// 当索引值小于数组长度就持续调用传入的fn函数
while (index < this.length) {
// 调用fn函数的返回值赋值给total变量保存
total = fn(total, this[index++], index, this);
}
// 遍历完数组后将total返回
return total;
};
var arr = [1, 2, 3, 5, 6, 78, 9, 20];
arr.ireduce((total, cur, index, arr) => total + cur);