zoukankan      html  css  js  c++  java
  • 数组reduce()的使用

    reduce()是这样定义的:reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。需要注意的是reduce()的回调函数在数组为空数组的时候是不会执行的。

    reduce()可以接收两个参数,第一个参数是回调函数(必须的),这个回调函数有四个参数:total(初始值或者返回的值,必须)、currentValue(当前操作的数组元素,必须)、currentIndex(当前元素的索引,可选)、arr(当前元素所属的数组,可选),第二个参数是设置回调函数的初始值(可选)

    应用1:简单数组的累加

            let arr = [1,2,3,4,5];
            let res = arr.reduce((total,item)=>{
                return total + item
            })
            console.log(res) //15    
            let arr = [1,2,3,4,5];
            let res = arr.reduce((total,item)=>{
                return total + item
            },10)
            console.log(res) //25

    应用2:操作对象,其实都一样

    const calendarTypeOptions = [
      { key: 'CN', display_name: 'China' },
      { key: 'US', display_name: 'USA' },
      { key: 'JP', display_name: 'Japan' },
      { key: 'EU', display_name: 'Eurozone' }
    ]
    
    const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
      acc[cur.key] = cur.display_name
      return acc
    }, {})
    
    console.log(calendarTypeKeyValue )
    //{ CN : "China", US : "USA" }

     

  • 相关阅读:
    oracle11g expdp/impdp数据库
    SqlServer触发器
    tomcat8.5.20配置https
    oracle常用函数积累
    Eclipse 搭建tomcat+动态项目完整版
    Windows7下ftp服务器
    Orcle定时生成表数据作业
    Oracle将一列值逗号拼接wm_concat函数
    Oracle表空间 ORA-01653:
    node+mongodb+ionic+cordova
  • 原文地址:https://www.cnblogs.com/zmyxixihaha/p/12175309.html
Copyright © 2011-2022 走看看