Array.reduce

Array.reduce() 是JavaScript中用于将数组元素累积计算为单个值的高阶函数,其核心作用是对数组中的每个元素执行一个累加器函数,最终返回累积结果。以下是详细用法和示例:
 
一、基本语法
 
array.reduce((accumulator, currentValue, currentIndex, array) => {
  // 累加逻辑
  return newAccumulator;
}, initialValue);
 
 
- 参数说明:
-  accumulator :累加器,保存上一次回调的结果。
-  currentValue :当前处理的数组元素。
-  currentIndex (可选):当前元素的索引。
-  array (可选):原数组。
-  initialValue (可选):累加器的初始值。
 
二、核心用法示例
 
1. 数组求和
 
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
 
 
- 初始值 0 传入后,累加过程为: 0 + 1 = 1  →  1 + 2 = 3  →  3 + 3 = 6  →  6 + 4 = 10  →  10 + 5 = 15 。
 
2. 对象数组分组
 
const people = [
  { name: 'A', age: 20 },
  { name: 'B', age: 25 },
  { name: 'C', age: 30 },
  { name: 'D', age: 20 }
];

const groupedByAge = people.reduce((acc, person) => {
  // 以age为键,将同年龄的人分组
  if (!acc[person.age]) {
    acc[person.age] = [];
  }
  acc[person.age].push(person);
  return acc;
}, {});

console.log(groupedByAge);
/* 输出:
{
  "20": [{ name: 'A', age: 20 }, { name: 'D', age: 20 }],
  "25": [{ name: 'B', age: 25 }],
  "30": [{ name: 'C', age: 30 }]
}
*/
 
 
3. 计算对象属性最大值
 
const products = [
  { price: 100 },
  { price: 150 },
  { price: 80 },
  { price: 200 }
];

const maxPrice = products.reduce((max, product) => {
  return product.price > max ? product.price : max;
}, 0);

console.log(maxPrice); // 200
 
 
三、初始值(initialValue)的作用
 
1. 提供初始累加值
 
- 若不传入 initialValue , reduce 会从数组第一个元素开始,将前两个元素作为初始 accumulator 和 currentValue 。
- 传入 initialValue 时,会从数组第一个元素开始,将 initialValue 作为初始 accumulator 。
 
2. 空数组的处理
 
- 数组为空且未传 initialValue 时,调用 reduce 会报错(无初始值)。
- 数组为空但传了 initialValue 时,直接返回 initialValue :
const emptyArray = [];
const result = emptyArray.reduce((acc, val) => acc + val, 100);
console.log(result); // 100(直接返回初始值)
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值