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;
    }
     
  • 相关阅读:
    Json2JsonArray JsonArray2StringArray
    循环结构
    类型转换代码
    字符串的截取拼接
    循环语句,选择结构的相关代码
    Java代码2-运算符简单运用
    Java代码1
    集合框架
    接口
    继承多态
  • 原文地址:https://www.cnblogs.com/jwenming/p/14574335.html
Copyright © 2011-2022 走看看