需求一
假設有一個數組,需要對其中的元素進行求和。
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));
