zoukankan      html  css  js  c++  java
  • JS中reduce方法

    定义和用法

    1.reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
    2.reduce() 可以作为一个高阶函数,用于函数的 compose
    3.reduce() 对于空数组是不会执行回调函数的

    浏览器支持

    支持谷歌、火狐、ie9以上等主流浏览器

    语法

    array.reduce(function(prev, current, currentIndex, arr), initialValue)
    

    prev:函数传进来的初始值或上一次回调的返回值
    current:数组中当前处理的元素值
    currentIndex:当前元素索引
    arr:当前元素所属的数组本身
    initialValue:传给函数的初始值

    初始值为数值:

      const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
           const sum = arr.reduce(function (prev, current) {
             return prev+current
           }, 0)
           console.log(sum) //55
    

    reduce根据函数传进来的初始值,不断回调叠加最终算出数组的和
    初始值为对象:

       const str = 'hello'
          const newstr = str.split('').reduce(function (prev, current) {
             const obj = {};
             obj[current] = current;
             prev.push(obj)
             return prev;
          }, [])
          console.log(newstr)
    

    结果为:

     [{
            h: 'h'
          },{
            e: 'e'
          },{
            l: 'l'
          },{
            l: 'l'
          },{
            o: 'o'
          }]
    

    如果初始值为数组,则返回的也是数组

    对象里的属性求和

    var result = [
        {
            subject: 'math',
            score: 10
        },
        {
            subject: 'chinese',
            score: 20
        },
        {
            subject: 'english',
            score: 30
        }
    ];
    
    var sum = result.reduce(function(prev, cur) {
        return cur.score + prev;
    }, 0);
    console.log(sum) //60
    
  • 相关阅读:
    【Hibernate 5】继承映射配置及多态查询
    【Hibernate 4】一对多映射配置
    【Hibernate 3】一对一映射配置
    【ITOO 2】使用ArrayList时的注意事项:去除多余的null值
    ubuntu查看端口占用
    ubuntu安装LAMP环境
    @ResponseBody返回不能正确接收
    ubuntu apt常用命令
    ubuntu添加sudo权限
    ubuntu 13.10 skype登不上问题
  • 原文地址:https://www.cnblogs.com/liliuyu/p/12581287.html
Copyright © 2011-2022 走看看