当前位置: 首页 > 工具软件 > Reduce > 使用案例 >

reduce函数详解

翟新
2023-12-01

基本概念:

reduce() 方法对数组中的每个元素按序执行一个由您提供的 reduce 函数,每一次运行 reduce 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

简单来说就是:执行传入函数,函数的返回值作为下一次的参数。

参数

reduce方法接受两个参数:reduce(callback,initialValue)
callback: functon(previousValue,currentValue,currentIndex,array)
四个参数的含义:
previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]。
currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]。
currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
array:用于遍历的数组。

实际用途

// 求数组元素的和
let sum = [0, 1, 2, 3].reduce(function (previousValue, currentValue) {
  return previousValue + currentValue
}, 0)
// 结果为6 
// 累加对象数组里的值
let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (previousValue, currentValue) {
    return previousValue + currentValue.x
}, initialValue)

console.log(sum) // logs 6
// 数组去重
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myArrayWithNoDuplicates = myArray.reduce(function (previousValue, currentValue) {
  if (previousValue.indexOf(currentValue) === -1) {
    previousValue.push(currentValue)
  }
  return previousValue
}, [])

console.log(myArrayWithNoDuplicates) // [a,b,c,d,e]
 类似资料: