reduce()

作者: 3e2235c61b99 | 来源:发表于2021-01-19 09:57 被阅读0次

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。

语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数

参数

以下为计算一个数组的和
不传入初始值时,从第一个参数开始
传入初始值时,从初始值开始

let arr = [1,2,3,4,5,6]
let result = arr.reduce((total, item) => {
    console.log(total, item)
    return total + item
})
console.log(result)

// 输出结果
// 1 2
// 3 3
// 6 4
// 10 5
// 15 6
// 21
let arr = [1,2,3,4,5,6]
let result2 = arr.reduce((total, item) => {
    console.log(total, item)
    return total + item
}, 10)
console.log(result2)

// 输出结果
// 10 1
// 11 2
// 13 3
// 16 4
// 20 5
// 25 6
// 31

相关文章

网友评论

      本文标题:reduce()

      本文链接:https://www.haomeiwen.com/subject/kekqzktx.html