数组降维,过滤,累加的实现

本文介绍了JavaScript中reduce方法的使用,包括数组的降维、过滤和累加操作。reduce方法的参数及工作原理被详细阐述,强调了initialValue的作用,并通过示例说明了如何自定义初始值。还探讨了利用reduce进行数组转换和过滤的实际应用。
摘要由CSDN通过智能技术生成

使用场景: reduce() 是一个有用的函数式编程技术,像是一般的累加,数组降维以及统计数组种出现的次数等等都可以通过该方法来实现;

接受参数:
1. Accumulator (acc) (累计器)
2. Current Value (cur) (当前值)
3. Current Index (idx) (当前索引)
4. Source Array (src) (源数组)

返回值:

  • accumulator 累计器
  • currentValue 当前值
  • currentIndex 当前索引
  • array 数组

为了方便理解,我们一般把accumulato设置为pre(前一个值),其中如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。

如何去理解initialValue呢?

我们将其看作是我们取值的一个初始值(就如英文翻译过来一样),它其实和我们当前的pre是一样的,只不过写上initialValue之后,相当于我们自己去自定义了一下当前的初始值。接下来我们直接看例子:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// 15

第一个log信息是我们在取值的时候没有加initialValue,就是默认的第一个值(pre即索引为0的那个数字’1’开始计算的),当我们加上了initialValue且取值为5的时候(第二个log),我们当前计算的pre改为了数字’5’,这时候会导致我们的计算值5 + 1 + 2 + 3 + 4, (注意,此时的currentValue是变成了第一个值“1”了,上一个log的时候currentValue是第二个值即“2”),此时的计算值就变成了15。

用官方的原话就是这样的:

回调函数第一次执行时,accumulator
和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供
initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

比如说执行这段代码:

console.log([20, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue
}, 10))
// 输出值为40

除此之外我们如果传的initialValue不是一个具体的数字,例如传一个空数组或者一个空对象,即表示我们当前的操作是将其转换为对应的格式,以下就是利用该特点实现的一个数组的降维。

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []
);
// flattened is [0, 1, 2, 3, 4, 5]

我们还可以通过reduce实现数组的过滤等:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const filter_evenNumbers = numbers.filter(number => number % 2 === 0)
// [2, 4, 6, 8, 10]
const reduce_evenNumbers = numbers.reduce((acc, number) => {
  if (number % 2 == 0) {
    acc.push(number)
  }
  return acc
}, [])
// [2, 4, 6, 8, 10]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值