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));
原文地址:https://www.cnblogs.com/liulei-cherry/p/10275986.html