zoukankan      html  css  js  c++  java
  • JavaScript Array Reduce用于数组求和

    需求一

    假设有一个数组,需要对其中的元素进行求和。

    const numbers = [1, -1, 2, 3];
    

    传统写法,使用for循环求和

    const numbers = [1, -1, 2, 3];
    
    let sum = 0;
    
    for(let n of numbers)
                sum += n;
            
    console.log(sum); // 5
    

    使用reduce求和

    reduce()函数的第一个参数是一个callback function,这个function中有2个参数,accumulator相当于sum,currentValue 是当前循环中数组的元素值。

    第二个参数是 accumulator 的初始值。

    返回值是一个数值。

    const sum = numbers.reduce((accumulator, currentValue) => {
             console.log('a', accumulator);
             console.log('c', currentValue);
             return accumulator + currentValue;
                
    }, 0);
    
    console.log(sum); // 5
    

    这其中发生了什么呢?

    每次循环的结果是:

    round 1   a = 0, c = 1 => a = 0+1 = 1
    round 2   a = 1, c = -1 => a = 0
    round 3   a = 0, c = 2 => a = 2
    round 4   a = 2, c = 3 => a = 5
    

    更简化的写法

    也可以不给 accumulator 的初始值,那么它的初始值就是数组的第一个元素, 这样可以少一次循环。

            const sum = numbers.reduce((accumulator, currentValue) => {
                console.log('a', accumulator);
                console.log('c', currentValue);
                return accumulator + currentValue;
            });
    

    把箭头函数简化为一行

            const sum = numbers.reduce(
                (accumulator, currentValue) => accumulator + currentValue
            );
            console.log(sum);
    

    需求二

    假设有一个数组,其中的既有正数,又有负数,分别对正负数求和,同时返回求和结果。

            const nums = [10, -12, 30, -1, -8, 0, 14, -33, 20];
    

    同时返回结果,那么返回值应该是一个对象,其中包含正数之和、负数之和。

    {
        plus: 0,
        minus: 0
    }
    

    完整解决方案:

            const nums = [10, -12, 30, -1, -8, 0, 14, -33, 20];
    
            function sumPlusMinus(arr) {
                return arr.reduce((acc, currentValue) => (
                    {
                        plus: currentValue > 0 ? acc.plus + currentValue : acc.plus,
                        minus: currentValue < 0 ? acc.minus + currentValue : acc.minus
                    }
    
                ), { plus: 0, minus: 0 });
            }
    
            console.log(sumPlusMinus(nums));
    
  • 相关阅读:
    [原创]java WEB学习笔记26:MVC案例完整实践(part 7)---修改的设计和实现
    [原创]java WEB学习笔记25:MVC案例完整实践(part 6)---新增操作的设计与实现
    [原创]java WEB学习笔记24:MVC案例完整实践(part 5)---删除操作的设计与实现
    [原创]java WEB学习笔记23:MVC案例完整实践(part 4)---模糊查询的设计与实现
    Tapestry IoC Configuration
    Tapestry IoC Decorator
    Tapestry IoC Service
    Tapestry-Again
    mysql error nr.1045 解决方法
    Bootstrap学习 导航
  • 原文地址:https://www.cnblogs.com/liulei-cherry/p/10275986.html
Copyright © 2011-2022 走看看