美文网首页
Reduce @mpjme

Reduce @mpjme

作者: 6659a0f02826 | 来源:发表于2017-08-10 22:56 被阅读14次
var orders={
  {amount:250},
  {amount:400},
  {amount:100},
  {amount:325}
}

// 需求:求和
// 一、以下是for循环写法
//var totalAmount =[];
//for(var i=0; i<order.length; i++){
//    totalAmount += orders[i].amount;
//}


// 二、以下是Reduce写法

var totalAmount = orders.reduce(function(sum,order){
    //console.log('hello' + sum, order)
    return sum + order.amount
},0)

 //箭头函数写法
//var totalAmount = orders.reduce((sum,order) =>  sum + order.amount ,0)

console.log(totalAmount)

  • reduce简介

对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。

  • 语法

array1.reduce(callbackfn[, initialValue])

  • 参数
  1. array1 必需。一个数组对象。
  2. callbackfn 必需。一个接受最多四个参数的函数。对于数组中的每个元素,reduce 方法都会调用 callbackfn 函数一次。
  3. initialValue 可选。如果指定 initialValue,则它将用作初始值来启动累积。第一次调用 callbackfn 函数会将此值作为参数而非数组值提供。
  • 返回值

通过最后一次调用回调函数获得的累积结果。

相关文章

  • Reduce @mpjme

    reduce简介 对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回...

  • Map @mpjme

    map简介 对数组的每个元素调用定义的回调函数并返回包含结果的数组。 语法 array1.map(callback...

  • Filter @mpjme

    filter简介 返回数组中的满足回调函数中指定的条件的元素。 语法 array1.filter(callback...

  • reduce方法详解总结

    1.reduce方法介绍: reduce语法:arr.reduce(callback,[initialValue]...

  • RxJava2.x-reduce语法

    一、reduce语法 日志 二、reduce方法2 日志 总结 1、reduce(BiFunction

  • js数组操作API(reduce的用法)

    1.reduce()的语法: 2.reduce()参数解释: callback : callback是reduce...

  • JS中数组的reduce方法

    1.reduce方法的介绍 reduce()时归并类方法。 1.1 reduce(fn,value): 1.1.1...

  • reduce的使用与案例

    reduce //reduce(callback,initiaValue)会传入两...

  • scala的reduce操作

    scala当中的reduce可以对集合当中的元素进行归约操作。 reduce包含reduceLeft和reduce...

  • js

    1、reduce arr.reduce(function(pre, cur, index, arr) { .......

网友评论

      本文标题:Reduce @mpjme

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