zoukankan      html  css  js  c++  java
  • Array.reduce()方法解析

    MDN上解释的很清楚, https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce  这儿再记录一下:

    定义:

    reduce() 方法对累加器和数组中的每个元素 (从左到右)应用一个函数,将其减少为单个值。

    语法:

    array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue);

    accumulator:上一次调用回调返回的值,或者是提供的初始值(initialValue)

    currentValue:数组中正在处理的元素

    currentIndex:数据中正在处理的元素索引,如果提供了 initialValue ,从0开始;否则从1开始

    array: 调用 reduce 的数组

    initialValue:可选项,其值用于第一次调用 callback 的第一个参数。如果没有设置初始值,则将数组中的第一个元素作为初始值。空数组调用reduce时没有设置初始值将会报错。

    浏览器兼容性:

    IE>=9 , PS: IE不支持ES6的箭头函数。

    应用:

    比如求和或者需要连续操作数组中的每个元素获得最终结果,for循环可以解决的可以尝试使用reduce方法来做。

    1. 求和。

    var res = [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { 
      return accumulator + currentValue;
    });

    callback 被调用四次,每次调用的参数和返回值如下表:

    callback accumulator currentValue currentIndex

    array

    return value
    first call 0 1 1 [0,1,2,3,4] 1
    second call 1 2 2 [0,1,2,3,4] 3
    third call 3 3 3 [0, 1, 2, 3, 4] 6
    fourth call 6 4 4 [0, 1, 2, 3, 4] 10


    2. 求最大值

    var res = [1,2,3,4,5].reduce((pre, curr) => {
        return curr > pre ? curr : pre;
    //return Math.max(pre,curr); });

    3. 将二维数组转化为一维数组

    var flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => {
        return a.concat(b);
    });
  • 相关阅读:
    给UILabel设置不同的字体和颜色
    通过btn获取所在cell
    常用网站
    如何设计一个 iOS 控件?(iOS 控件完全解析) (转)
    #Mac技巧#如何在Mac系统上新建TXT文档,以及打开txt文稿的乱码问题如何解决
    整理 iOS 9 适配中出现的坑(图文)(转)
    UISegmentedControl
    Xcode因为证书问题经常报的那些错
    iOS开发--UIDatePicker
    IOS开发中有用的第三方库
  • 原文地址:https://www.cnblogs.com/gogolee/p/7453817.html
Copyright © 2011-2022 走看看