zoukankan      html  css  js  c++  java
  • 数组的reduce函数

    reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。(汇合

    先看个例子

    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    
    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10
    
    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15

     reduce为数组中的每一个元素依次执行callback函数(reducer函数),

    reducer 函数接收4个参数:

    1. Accumulator (acc) (累计器)
    2. Current Value (cur) (当前值)
    3. Current Index (idx) (当前索引)
    4. Source Array (src) (源数组)

    回到函数第一次执行时,accumulator 和currentValue的取值有两种情况:

    1、如果调用reduce()时提供了initialValueaccumulator取值为initialValuecurrentValue取数组中的第一个值;

    2、如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

    手写reduce

    Array.prototype.myReduce = function(fn, base){
        if(this.length === 0 && !base){
            throw new Error('出错了')
        }
        for(let i = 0; i < this.length; i++){
            if(!base){
                base =  fn(this[i],this[i+1], i, this)
            }
            else{
                base = fn(base,this[i],i,this)
            }
        }
        return base;
    }
     
  • 相关阅读:
    LeetCode 42. Trapping Rain Water
    LeetCode 209. Minimum Size Subarray Sum
    LeetCode 50. Pow(x, n)
    LeetCode 80. Remove Duplicates from Sorted Array II
    Window10 激活
    Premiere 关键帧缩放
    AE 「酷酷的藤」特效字幕制作方法
    51Talk第一天 培训系列1
    Premiere 视频转场
    Premiere 暴徒生活Thug Life
  • 原文地址:https://www.cnblogs.com/jwenming/p/14574335.html
Copyright © 2011-2022 走看看