JS中reduce方法详解

reduce() 是 JavaScript 数组的一个内置方法,用于对数组中的每个元素执行一个由你提供的 reducer 函数(升序执行),将其减少为单个输出值。

基本语法

arr.reduce((accumulator,currentValue,index,array)=>{},initialValue)
  • callBack:()=>{} (必需):一个执行数组中每个值的函数,包含四个参数。
    • accumulator (累积器):累积回调函数的返回值;它是上一次调用回调时返回的累积值。
    • currentValue (当前值):数组中正在处理的当前元素。
    • index (可选):数组中正在处理的当前元素的索引。
    • array (可选):调用 reduce() 的数组。
  • initialValue (可选):作为第一次调用 callback 函数时的第一个参数的值。如果没有提供初始值,则将使用数组中的第一个元素。在没有初始值的空数组上调用 reduce 将报错。

示例

  1. 计算数组的总和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出:15
  1. 将数组中的对象合并为一个对象
const objects = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const merged = objects.reduce((accumulator, currentValue) => {
  accumulator[currentValue.id] = currentValue.name;
  return accumulator;
}, {});

console.log(merged); // 输出:{ '1': 'Alice', '2': 'Bob', '3': 'Charlie' }
  1. 使用初始值
const numbers = [1, 2, 3, 4, 5];
const sumWithInitial = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 10);
console.log(sumWithInitial); // 输出:25 (10 + 1 + 2 + 3 + 4 + 5)
  1. 数组去重
const array= [1, 2, 3, 4, 5,5,4,3,2,1];
const newArray= array.reduce((pre, cur) => {
	if(!pre.includes(cur)){
		pre.push(cur)
	}
},[]);
console.log(sumWithInitial); // 输出:[1,2,3,4,5]

注意点

  • reduce() 不会改变原始数组,而是返回一个新值。
  • 如果没有提供 initialValuereduce() 会使用数组的第一个元素作为初始值,并且从第二个元素开始执行回调函数。
  • 如果数组为空且没有提供 initialValuereduce() 会抛出 TypeError

reduce() 是一个非常强大的函数,可以用于执行各种复杂的数组转换和操作。通过灵活地使用回调函数和初始值,你可以实现各种功能,从简单的求和到复杂的对象合并和转换。

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值