不要着急,不要着急,

休息,休息一会。

reduce方法的使用

  reduce(收敛):接收一个回调函数作为累加器,数组中的每个值(从左到右)开始缩减,最终为一个值,是ES5中新增的又一个数组逐项处理方法。

  reduce(callback,initialValue)

  callback(一个在数组中每一项上调用的函数,接受四个函数:)

    • previousValue(上一次调用回调函数时的返回值,或者初始值)
    • currentValue(当前正在处理的数组元素)
    • currentIndex(当前正在处理的数组元素下标)
    • array(调用reduce()方法的数组)

               initialValue(可选的初始值。作为第一次调用回调函数时传给previousValue的值)

//基本数组的求和
        let arr1 = [1,2,3,4,5,6,7];
        let sum = arr.reduce((pre,next)=>{
            return pre+next;
        });
        console.log(sum);

//用于对象数组的求和就需用到第二个参数
        let arr1 = [{count:3,price:2},{count:1,price:5},{count:5,price:1}];
        let sum = arr.reduce((pre,next)=>{
            return pre+next.count*next.price;
        },0);//0作为第一次遍历pre的值,相当于在数组前插入0这个元素
        console.log(sum);

 

posted @ 2019-08-25 20:51  angle-xiu  阅读(600)  评论(1编辑  收藏  举报
Live2D