JS reduce

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方法有四个参数

  • accumulator(简称acc)
  • current value(简称cur)
  • current index(简称idx)
  • source array(简称src)

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方法中,参数如下:

  • callback
    a function to execute on each element in the array (except for the first, if no initialValue is supplied), taking four arguments
    一个计算数组里每一项的方法(第一个参数),这个方法可以携带四个参数
  • initialValue
    a value to use as the first argument to the first call of the callback. if no initialValue is supplied, the first element in the array will be used and skipped.Calling reduce() on an empty array without an initialValue will throw a TypeError.
    一个被用在callback的初始值,如果没有初始值,则数组中的第一个值会被使用并跳过;如果一个空数组使用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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容