JS数组Reduce()方法详解及高级技巧-即看即用

背景:

写这篇文章其实没啥必要,但是看到csdn有很多`小可爱`写了文章设置要VIP`还XX挺多文章都设置`,我寻思这玩意就是看个文章、关键字帮助回忆,所以本着`方便`原则,写了个基础的:

1.reduce() 是 JavaScript 中数组的一个高阶函数,它用于累积数组的元素,将它们合并为一个单一的值。这个方法接受一个回调函数作为参数,这个回调函数可以用来执行对数组中的每个元素的操作,累积的结果会不断传递给下一轮的回调。

下面是关于 reduce() 方法的详解和一些高级技巧:

基本语法:

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

callback: 用于处理数组中每个元素的回调函数。

accumulator: 累积器,累积回调函数的返回值。
currentValue: 数组当前被处理的元素。
currentIndex(可选): 数组当前被处理元素的索引。
array(可选): 调用 reduce 的数组。
initialValue(可选): 作为第一次调用回调函数时的第一个参数的值。如果没有提供,则使用数组的第一个元素作为初始值,并从第二个元素开始调用回调。

基本示例:

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 输出 15

在这个例子中,reduce 从数组 [1, 2, 3, 4, 5] 中累积元素,初始值为 0,每次将当前元素加到累积器上。

高级技巧:

1.不提供初始值:
如果不提供初始值,reduce 会使用数组的第一个元素作为初始值,然后从第二个元素开始执行回调。

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

const product = numbers.reduce((accumulator, currentValue) => {
  return accumulator * currentValue;
});

console.log(product); // 输出 120

2.使用箭头函数简化:

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

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

console.log(sum); // 输出 15

3.将数组转为对象:

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

const fruitObject = fruits.reduce((acc, fruit) => {
  acc[fruit] = true;
  return acc;
}, {});

console.log(fruitObject); // 输出 { apple: true, banana: true, orange: true }

4.Flatten 数组:

const nestedArrays = [[1, 2], [3, 4], [5, 6]];

const flatArray = nestedArrays.reduce((acc, array) => acc.concat(array), []);

console.log(flatArray); // 输出 [1, 2, 3, 4, 5, 6]

5.计算数组中每个元素的出现次数:

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

const wordCount = words.reduce((acc, word) => {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {});

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

reduce() 是一个非常强大的数组方法,可以通过不同的应用场景发挥其威力。在使用时,根据具体情况选择是否提供初始值,以及如何编写回调函数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值