Reduce @mpjme

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 函数会将此值作为参数而非数组值提供。
  • 返回值

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容