JS数组reduce()方法使用

淩亂°似流年 2023-06-06 03:41 114阅读 0赞

定义和用法

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’,

    1. '192.168.81.24','192.168.81.25','192.168.81.23'];

    let m = arrays.reduce((pdata, nowdata, index, ars)=>{

    1. if(nowdata in pdata) {
    2. pdata[nowdata]++;
    3. } else {
    4. pdata[nowdata] = 1
    5. }
    6. return pdata

    }, {});//统计次数 — 即返回对象 决定了参数是对象

在这里插入图片描述

  • 第二去重

    let arrays = [‘192.168.81.21’,’192.168.81.21’,’192.168.81.22’,’192.168.81.23’,

    1. '192.168.81.24','192.168.81.25','192.168.81.23'];

    let n= arrays.reduce((pred, nowd) => {

    1. if(!pred.includes(nowd)) {
    2. // pred.push(nowd);
    3. pred = pred.concat(nowd)
    4. }
    5. return pred;

    }, []);//去重 reduces决定了参数是数组

在这里插入图片描述

  • 第三返回多种数据格式

    let arrays = [1,’c#’,2,’c++’,3,’css’,’js’,4,5.2,’java’];
    let [intarr, strarr] = arrays.reduce((array, exampleValue) => {

    1. if(typeof(exampleValue) == "number") {
    2. array[0].push(exampleValue);
    3. }
    4. if(typeof(exampleValue) == "string") {
    5. array[1].push(exampleValue)
    6. }
    7. return array;

    }, [[], []]);//返回二维数组

在这里插入图片描述


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

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JS reduce()方法详解

    > reduce()方法可以搞定的东西,for循环,或者forEach方法有时候也可以搞定,那为啥要用reduce()?这个问题,之前我也想过,要说原因还真找不到,唯一能找到的