JS数组reduce()方法使用

定义和用法

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

语法

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数(重点理解回调的两个参数)

第一个参数(callback):function(total, currentValue, currentIndex, arr)

  • previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
  • currentValue (数组中当前被处理的元素)
  • index (当前元素在数组中的索引)
  • array (调用 reduce 的数组)

第二个参数:initialValue (作为第一次调用 callback 的第一个参数。) ,该值也决定了返回值类型

  • 如果不给这个值,那么默认从第二项开始遍历,如果数组为空则异常

使用

源码:
链接:https://pan.baidu.com/s/1jd7Vs7Eth_Jh-rMNZqJRSA
提取码:0iuv

  • 第一统计:ip计数,或者单词统计
let arrays = ['192.168.81.21','192.168.81.21','192.168.81.22','192.168.81.23',
					'192.168.81.24','192.168.81.25','192.168.81.23'];
let m = arrays.reduce((pdata, nowdata, index, ars)=>{ 
        if(nowdata in pdata) {
            pdata[nowdata]++;
        } else {
            pdata[nowdata] = 1
        }
        return pdata
 }, {});//统计次数 -- 即返回对象   决定了参数是对象  

在这里插入图片描述

  • 第二去重
let arrays = ['192.168.81.21','192.168.81.21','192.168.81.22','192.168.81.23',
					'192.168.81.24','192.168.81.25','192.168.81.23'];
let n= arrays.reduce((pred, nowd) => {
        if(!pred.includes(nowd)) {
            // pred.push(nowd);
            pred = pred.concat(nowd)
        }
        return pred;
}, []);//去重  reduces决定了参数是数组

在这里插入图片描述

  • 第三返回多种数据格式
 let arrays = [1,'c#',2,'c++',3,'css','js',4,5.2,'java'];
 let [intarr, strarr] = arrays.reduce((array, exampleValue) => {
        if(typeof(exampleValue) == "number") {
            array[0].push(exampleValue);
        }
        if(typeof(exampleValue) == "string") {
            array[1].push(exampleValue)
        }
        return array;
}, [[], []]);//返回二维数组

在这里插入图片描述


用到这里的原因,我的可视化记一笔中,在前端统计访问api次数

发布了55 篇原创文章 · 获赞 29 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/ljcc122/article/details/102467468
今日推荐