首页 » 技术分享 » sum(1),sum(2,3,4),sum(2)(3)(4)

sum(1),sum(2,3,4),sum(2)(3)(4)

 
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <script>
    //案例1
    //sum(2,3)和sum(2)(3)均能输出outPut5,这个问题较为简单,只要返回一个函数即可,本例中使用了es6语法
    function sum(x = 0, y) {
      if ([...arguments][1] == undefined) {
        let befor = [...arguments][0];
        return function suum(afte) {
          let sum2 = befor + afte;
          console.log(`outPut${sum2}`);
        }
      } else {
        let sum1 = x + y;
        console.log(`outPut${sum1}`);
      }
    }

    sum(2, 3); //输出outPut5
    sum(2)(3); //输出outPut5

    //案例二、add(2,3,4...)和add(2)(3)(4)...都输出相同结果的解决方案

    function add(x) {
      var sum = x;
      var tmp = function (y) {
        sum = sum + y;
        return tmp;
      };
      tmp.toString = function () {
        return sum;
      };
      return tmp;
    }
    console.log(add(1)(2)(3)); //6
    console.log(add(1)(2)(3)(4)); //10
    console.log(add(1)(2)(3)(4)(5)); //15
    console.log(add(1)(2)(3)(4)(5)(6)); //21

    //扩展案例3、此函数使用es6实现输入sum(),sum(2,3,4...)多个值相加,还有sum(2)(3)(4)...等多个数值分别相加的值相等,此案例也是最完整的解决方案
    function sum(...args) {
      if ([...args].length == 1) {
        let sum2 = [...args][0];
        var suum = function (y) {
          sum2 += y;
          console.log(`output ${sum2}`)
          return suum;
        }
        //suum.valueOf = function () {
        suum.toString = function () {
          return sum2;
        }
        return suum;
      } else {
        let sum1 = 0;
        for (var i = 0; i < [...args].length; i++) {
          sum1 += [...args][i];
        }
        return sum1
      }
    }
    //sum(1); //outPut1 0
    //sum(2, 3, 4); //outPut1 9
    //sum(2)(3)(4)(5); //outPut1 5//outPut1 9//outPut1 14
    //每加一次就会输出一次Sum。如果不想输出三次则可以在函数中加一个valueOf方法或者toString方法。然后将Summ函数中的console去掉。
    //然后console.log(sum(2)(3)(4)(5));即可
    console.log(sum(2)(3)(4)(5))
    console.log(sum(2))
  </script>
</body>
</html>

 

转载自原文链接, 如需删除请联系管理员。

原文链接:sum(1),sum(2,3,4),sum(2)(3)(4),转载请注明来源!

0