reduce 的中文详解

JavaScript 数组方法 reduce 的全面指南

什么是 reduce?

reduce() 是 JavaScript 中数组的一个高阶函数,用于将数组中的所有元素“归约”为一个单一的值。 它通过一个“累加器”(accumulator)逐个处理数组元素,最终返回累加结果。

基本语法

array.reduce(callback(accumulator, currentValue, index, array), initialValue)

常用示例

1. 求数组总和

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

const sum = numbers.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // 输出: 10

2. 将数组转为对象(按 ID 索引)

const users = [

  { id: 1, name: '张三' },

  { id: 2, name: '李四' }

];

const userMap = users.reduce((acc, user) => {

  acc[user.id] = user;

  return acc;

}, {});

console.log(userMap);

3. 统计数组中各元素出现次数

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const count = fruits.reduce((acc, fruit) => {

  acc[fruit] = (acc[fruit] || 0) + 1;

  return acc;

}, {});

console.log(count); // { apple: 3, banana: 2, orange: 1 }

注意事项

适用场景

当你需要将数组“压缩”成一个值时,比如: