JS reduce

2019-10-16  本文已影响0人  我的天气很好啦

the reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
web doc里,reduce方法的定义是,你提供一个reducer方法去操作数组里每一项,最后会返回操作结果的值。

the reducer function takes four arguments
reducer方法有四个参数

your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array ultimately becomes the final, single resulting value.
你的reduce()方法最后返回的是accumulator,accumulator的值会通过操作数组的每一项来得到最终的唯一的结果。

在reduce方法中,参数如下:

例如:

const array = [1,2,3,4]
const reducer = (accumulator, currentValue) => accumulator + currentValue

console.log(array.reduce(reducer))
// expected output: 10

console.log(array.reduce(reducer, 6))
// expected output: 16

上一篇 下一篇

猜你喜欢

热点阅读