JS reduce

作者: 我的天气很好啦 | 来源:发表于2019-10-16 15:45 被阅读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方法有四个参数

    • 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
    
    

    相关文章

      网友评论

          本文标题:JS reduce

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