美文网首页
myReduce实现

myReduce实现

作者: 织雪纱奈 | 来源:发表于2021-07-15 16:06 被阅读0次
    Array.prototype.myReduce = function(reducer, initialValue) {
        const hasInitial = arguments.length > 1;
        let ret = hasInitial ? initialValue : this[0];
        for (let i = hasInitial ? 0 : 1; i < this.length; i++) {
            ret = reducer.call(undefined, ret, this[i], i, this);
        }
        return ret;
    }
    
    // 或者极简版本
    Array.prototype.myReduce = function(reducer, initialValue) {
        let ret = initialValue;
        for (let i = 0; i < this.length; i++) {
            ret = reducer(ret, this[i], i, this);
        }
        return ret;
    }
    

    some filter https://chaiguanpeng.github.io/2018/05/29/js%E6%95%B0%E7%BB%84%E4%B8%ADfilter%E3%80%81map%E3%80%81reduce%E3%80%81find%E7%AD%89%E6%96%B9%E6%B3%95%E5%AE%9E%E7%8E%B0%E7%9A%84%E5%8E%9F%E7%90%86/

    相关文章

      网友评论

          本文标题:myReduce实现

          本文链接:https://www.haomeiwen.com/subject/xnfmpltx.html