reduce原理
let arr = [10, 20, 30];
Array.prototype.myreduce = function (fn, initVal) {
for (let i = 0; i <= this.length - 1; i++) {
initVal = fn(initVal, this[i], i, this);
}
return initVal;
};
let r1 = arr.myreduce(function (p, n) {
return p + n;
}, 0);
console.log(r1);
reduceRight原理
Array.prototype.myreduceRight = function (fn, initVal) {
if (!initVal) initVal = 0;
for (let i = this.length - 1; i >= 0; i--) {
initVal = fn(initVal, this[i], i, this);
}
return initVal;
};
let r2 = arr.myreduceRight(function (p, n) {
return p + n;
}, 0);
console.log(r2);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。