数组的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>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值