• 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);

  • 相关阅读:
    电容的串联和并联的性质
    start.sh
    shell 得到当前目录路径
    Java程序远程无法执行nohup命令
    mysql windows 安装5.7
    电阻并联的性质
    电阻串联的性质
    webjars
    邮箱设置
    万用表使用注意事项
  • 原文地址:https://www.cnblogs.com/angle-xiu/p/11409303.html
Copyright © 2020-2023  润新知