使用for循环实现
Array.prototype.forReduce = function (callback,prev) {
for (let i = 0; i < this.length; i++) {
if (typeof prev === "undefined") {
prev = callback(this[i], this[i + 1], i + 1, this);
} else {
prev = callback(prev, this[i], i, this);
}
}
return prev;
};
let n = 0;
let r1 = [1, 2, 3, 4, 5, 6, 7].forReduce(function (prevValue, currentValue, currentIndex, array) {
n++;
console.log('调用'+ n + "次");
return prevValue + currentValue;
},22);
console.log(r1);
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210323102628910.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hlTWlzdGVy,size_16,color_FFFFFF,t_70)
for循环实现参考
使用递归实现
Array.prototype.reduceRecursion = function(callback, prev){
if(Array.isArray(this) && this.length>0){
var activeIndex = 0;
var last = this.length-1;
var that = this;
prev = prev || 0;
function item (activeIndex, initValue) {
if(activeIndex === last){
prev += that[activeIndex];
return prev;
}
if(!initValue){
prev += callback(that[activeIndex], that[activeIndex + 1], activeIndex + 1, that);
activeIndex++;
} else {
prev += callback(prev, that[activeIndex], activeIndex, that);
}
activeIndex++;
return item(activeIndex);
}
return item(activeIndex, prev);
}else{
throw new Error('必须是不为空的数组');
}
};
var arr = [1,2,3,4,5,6,7];
var n = 0;
var result = arr.reduceRecursion(function(s,c) {
n++;
console.log('调用'+ n + "次");
return s + c;
});
console.log(result);
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210323170010442.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hlTWlzdGVy,size_16,color_FFFFFF,t_70)