代码之家  ›  专栏  ›  技术社区  ›  brk

如果一个参数包含多个值,如何使用curring函数?

  •  3
  • brk  · 技术社区  · 6 年前

    我有一个高阶函数,尽管第一个例子 multiply(4,5) 按预期工作,但是否可以像 multiply(2)(4, 5) . 在这种情况下,答案是8,但是否可以以这样的方式创建一个循环函数,从而得出40

    function multiply(s) {
      return function(b) {
        return s * b;
      }
    
    }
    
    console.log(multiply(4)(5))
    console.log(multiply(2)(4, 5))
    4 回复  |  直到 6 年前
        1
  •  4
  •   Nina Scholz    6 年前

    你可以使用 rest parameters ... 并收集两个函数上的所有参数并返回约化结果。

    function multiply(...a) {
        return function(...b) {
            return [...a, ...b].reduce((a, b) => a * b);
        };
    }
    
    console.log(multiply(4)(5));       //  20
    console.log(multiply(2)(4, 5));    //  40
    console.log(multiply(3, 2)(4, 5)); // 120
        2
  •  2
  •   manish kumar    6 年前

    function multiply(s) {
      return function(b) {
        for(key in arguments)s*=arguments[key];
        return s;
      }
    
    }
    
    console.log(multiply(4)(5))
    console.log(multiply(2)(4, 5))

    我认为在您的案例中最好使用arguments属性。

        3
  •  1
  •   Linschlager Maulik Dhameliya    6 年前

    你可以用 arguments :

    function multiply(s) {
      return function () {
        return Array.from(arguments).reduce(function(accumulator, currentValue) {
          return accumulator * currentValue;
        }, s);
      }
    }
    
        4
  •  0
  •   Alexandre Elshobokshy    6 年前

    如果你有一个或多个这样做 b 争论:

    function multiply(s) {
      // Will contain the multiplication of all b arguments
      var result = 1;
    
      // ...b will return an the array arguments passed
      return function(...b) {
    
        // Loop through each of this array and update result
        for (var i = 0; i < b.length; i++) {
          result *= b[i];
        }
    
        // return the final result
        return s * result;
      }
    
    }
    
    console.log(multiply(4)(5))
    console.log(multiply(2)(4, 5))