数组的reduce 的使用和扁平化处理

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 数组的reduce / reduceRight迭代方法
    // reduce可以再迭代数组每一项的同时,实现结果的累积!在callback函数中
    //   + result: 存储的是上一轮处理的结果「也可能是数组第一项的值」
    //   + item: 当前选代这一项
    //   + index: 迭代这一项的索引
    // 函数返回的值作为本轮处理的结果!!整个循环迭代结束后,把最后一轮的返回值,作为reduce执行的总结果!!
    // reduce中传递的第二个参数,是为了给result赋值初始值的!
    let arr = [10, 20, 30, 40]

    let res = arr.reduce((result, item, index) => {
      //第一轮:result数组第一项的值10 数组从第二项开始迭代:item=20 index=1 返回30
      //第二轮:result是第一轮返回的结果30 item=30 index=2 返回60
      // 第三轮:result是第二轮返回的结果60 item=40 index=3返回100
      return result + item
    })
    // let res = arr.reduce((result, item, index) => {
    //   第一轮:result是100 数组从第一项开始迭代:item=10 index=0 返回110
    //   第二轮:result是110 item=20 index=1 返回130
    //   ...
    //   return result + item
    // },100)
    // console.log(res)


    const a = x => x + 10
    const b = x => x - 10
    const c = x => x * 10
    const d = x => x / 10
    // 需求给定一个值100,依次执行上面的四个函数返回结果要怎么实现
    const compose = function compose (...funcs) {
      //funcs -> [a,b,c,d]
        funcs.forEach(item => {
        if (typeof item !== "function") {
          throw new TypeError('传递进来的值必须为函数')
        }
      })
      return function handle (x) {
        //x=>100
        let len = funcs.length
        if (len === 0) return x
        if (len === 1) return funcs[0](x)
        return funcs.reduce((result, func, index) => {
          //第-轮:result=x(100)func=a index=0 返回 a(100)=>110
          //第二轮:result=110 func=b index=1 返回 b(110)=>100
          // ...
          return func(result)
        }, x)
      }

    }
    console.log(compose(a, b, c, d)(100)); 
  </script>
</body>

</html>

相关推荐

  1. reduce 使用扁平处理

    2024-03-19 17:30:07       36 阅读
  2. 15.实现扁平

    2024-03-19 17:30:07       51 阅读
  3. 前端 、Python 扁平嵌套应用场景

    2024-03-19 17:30:07       27 阅读
  4. Reducer Context实现简单Redux

    2024-03-19 17:30:07       62 阅读
  5. c# 使用

    2024-03-19 17:30:07       37 阅读
  6. c#使用

    2024-03-19 17:30:07       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-19 17:30:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-19 17:30:07       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-19 17:30:07       82 阅读
  4. Python语言-面向对象

    2024-03-19 17:30:07       91 阅读

热门阅读

  1. 在事务里发送普通消息引起的线上问题

    2024-03-19 17:30:07       45 阅读
  2. C# 通信断线重连问题说明与示例

    2024-03-19 17:30:07       45 阅读
  3. Springboot AOP

    2024-03-19 17:30:07       43 阅读
  4. 在MATLAB中进行并行计算和GPU加速?

    2024-03-19 17:30:07       46 阅读
  5. fedora RTL8821CE 无线网卡驱动安装

    2024-03-19 17:30:07       45 阅读
  6. 人工智能入门学习笔记2:人工智能学习资料

    2024-03-19 17:30:07       46 阅读
  7. ffmpeg视频剪辑

    2024-03-19 17:30:07       40 阅读