zoukankan      html  css  js  c++  java
  • 闭包实现add(1)(2), add(1,2)的功能

    function add(x, y) {
        // 当实参的数量大于等于2时,则此时返回前两个参数之和
        if (arguments.length >= 2) {
          return x + y;
        }
        // 当实参的数量为1时,此时返回一个带一个参数的匿名函数,当执行此匿名函数的时候返回外层和内部函数之和
        else if (arguments.length == 1) {
          return function (z) {
            return x + z;
          }
        }
        // 如果没有传参数时,则直接返回undefined
        else if (arguments.length == 0) {
          return undefined;
        }
      }
      // 执行结果检验
      console.log(add(1, 2)); // 3
      console.log(add(1)); //f(z)
      console.log(add(1)(3));
      console.log(add(1)(2)); // 3
      console.log(add(1, 2, 3, 4)); // 3
     
    //优化版本 使a(1)的时候输出的不是匿名函数
    function add(x, y) {
        // 当实参的数量大于等于2时,则此时返回前两个参数之和
        if (arguments.length >= 2) {
          return x + y;
        }
        // 当实参的数量为1时,此时返回一个带一个参数的匿名函数,当执行此匿名函数的时候返回外层和内部函数之和
        else if (arguments.length == 1) {
          function sum(b) {
            x = x + b
            return sum
          }
          sum.toString = function () {
            return x
          }
          return sum
        }
        // 如果没有传参数时,则直接返回undefined
        else if (arguments.length == 0) {
          return undefined;
        }
      }
      // 执行结果检验
      console.log(add(1, 2)); // 3
      console.log(add(1)); //1
      console.log(add(1)(3));  //4
      console.log(add(1)(2)); // 3
      console.log(add(1, 2, 3, 4)); // 3
     
    reduce方法实现累加
    // // add(1,2,3,4,5,6)
      // function add(...args) {
      //   return args.reduce((prev, val) => {
      //     return prev + val
      //   }, 0)
      // }
  • 相关阅读:
    windows下Yarn安装与使用(两种方法)
    git配置公钥---解决码云出现git@gitee.com: Permission denied (publickey)
    npm使用国内镜像的两种方法
    【LeetCode】33. Search in Rotated Sorted Array (4 solutions)
    【LeetCode】83. Remove Duplicates from Sorted List
    【LeetCode】82. Remove Duplicates from Sorted List II
    【LeetCode】85. Maximal Rectangle
    【LeetCode】84. Largest Rectangle in Histogram
    【LeetCode】87. Scramble String
    【LeetCode】162. Find Peak Element (3 solutions)
  • 原文地址:https://www.cnblogs.com/memeflyfly/p/14236021.html
Copyright © 2011-2022 走看看