Global Objects

.reduce()

2025-06-03

.reducer() 会遍历整个数组,并把当前的元素和之前的结果相加。

语法

reduce(callbackFn)
reduce(callbackFn, initialValue)
  • callbackFn: 数组中每个元素执行的函数
  • initialValue: 第一次调用 callbackFn 时的值,如果不指定则为数组第一个值。

使用

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
console.log(sumWithInitial);
// Expected output: 10