以封闭的方式在javascript中乘以3个数字

ven*_*usa 2 javascript

    function()
    {

    }
    function(2,3,4)//24
    function(2,3)(4)//24
    function(2)(3)(4)//24
Run Code Online (Sandbox Code Playgroud)

我无法实现这种乘法,请解释我如何实现这一目标?任何形式的帮助都非常感谢!

Cer*_*nce 6

如果到目前为止提供的参数总数小于3,您可以使用带有绑定参数的函数返回:

const multiply = (...args) => (
  args.length < 3
  ? multiply.bind(null, ...args)
  : args.reduce((a, b) => a * b)
);
console.log(multiply(2, 3, 4));
console.log(multiply(2, 3)(4));
console.log(multiply(2)(3)(4));
console.log(multiply(2)(3, 4));
Run Code Online (Sandbox Code Playgroud)


Hit*_*ua1 3

    function curry(func,args,space) {
        var n  = func.length - args.length; //arguments still to come
        var sa = Array.prototype.slice.apply(args); // saved accumulator array
        function accumulator(moreArgs,sa,n) {
            var saPrev = sa.slice(0); // to reset
            var nPrev  = n; // to reset
            for(var i=0;i<moreArgs.length;i++,n--) {
                sa[sa.length] = moreArgs[i];
            }
            if ((n-moreArgs.length)<=0) {
                var res = func.apply(space,sa);
                // reset vars, so curried function can be applied to new params.
                sa = saPrev;
                n  = nPrev;
                return res;
            } else {
                return function (){
                    // arguments are params, so closure business is avoided.
                    return accumulator(arguments,sa.slice(0),n);
                }
            }
        }
        return accumulator([],sa,n);
    }
    // now you can define any type of function, add, Mul etc...
    function add (a,b,c){
          if (arguments.length < this.add.length) {
            return curry(this.add,arguments,this);
          }
          return a+b+c;
    }

    function mul (a,b,c){
        if (arguments.length < this.mul.length) {
          return curry(this.mul,arguments,this);
        }
        return a*b*c;
    }

    // Multiplication
    console.log("Multiplication Sample");
    console.log(mul(2,3,4))         // 24
    console.log(mul(2,3)(4))        // 24
    console.log(mul(2)(3)(4))       // 24
    console.log(mul()(1,2,4));      // 8
    console.log(mul(1)(2)(5));      // 10
    console.log(mul(1)()(2)()(6));  // 12

    // Addition
    console.log("Addition Sample");
    console.log(add(2,3,4))         // 9
    console.log(add(2,3)(4))        // 9
    console.log(add(2)(3)(4))       // 9
    console.log(add()(1,2,4));      // 7
    console.log(add(1)(2)(5));      // 8
    console.log(add(1)()(2)()(6));  // 9
Run Code Online (Sandbox Code Playgroud)

参考:http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html