使用递归或者for循环实现一个reduce

使用for循环实现

/**
 *
 * @param callback  为传入的回调函数
 * @param prev  为初始值
 */
Array.prototype.forReduce = function (callback,prev) {
    //遍历this 数组
    for (let i = 0; i < this.length; i++) {
        //判断有没有设置初始值
        if (typeof prev === "undefined") {
            //没有初始值,则调用callback,转入当前值,下一个值,当前index为下一个,当前数组
            prev = callback(this[i], this[i + 1], i + 1, this);
        } else {
            //有初始值,则调用callback,传入prev为第一个值,第二个为当前的i,当前index为i,当前数组
            prev = callback(prev, this[i], i, this);
        }
    }
    return prev;
};
let n = 0; // 判断function执行次数 
let r1 = [1, 2, 3, 4, 5, 6, 7].forReduce(function (prevValue, currentValue, currentIndex, array) {
	n++; // 判断function执行次数 
    console.log('调用'+ n + "次"); // 判断function执行次数 
    return prevValue + currentValue;
},22);
 
console.log(r1);

在这里插入图片描述

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; // 判断function执行次数 
var result = arr.reduceRecursion(function(s,c) {
	n++; // 判断function执行次数 
    console.log('调用'+ n + "次"); // 判断function执行次数 
	return s + c;
});
console.log(result);

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值