47

我想让这种语法成为可能:

var a = add(2)(3); //5

根据我在http://dmitry.baranovskiy.com/post/31797647阅读的内容

我不知道如何使它成为可能。

4

31 回答 31

103

您需要 add 成为一个函数,该函数接受一个参数并返回一个函数,该函数接受一个将参数添加到 add 和自身的参数。

var add = function(x) {
    return function(y) { return x + y; };
}
于 2010-02-16T12:49:54.653 回答
39
function add(x) {
    return function(y) {
        return x + y;
    };
}

啊,JavaScript之美

这种语法也很简洁

function add(x) {
    return function(y) {
        if (typeof y !== 'undefined') {
            x = x + y;
            return arguments.callee;
        } else {
            return x;
        }
    };
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6
于 2010-02-16T12:52:01.653 回答
15
function add(x){
  return function(y){
    return x+y
  }
}

一流的函数闭包可以完成这项工作。

于 2010-02-16T12:50:20.697 回答
14

这是关于 JS curring 并且有点严格valueOf

function add(n){
  var addNext = function(x) {
    return add(n + x);
  };

  addNext.valueOf = function() {
    return n;
  };

  return addNext;
}

console.log(add(1)(2)(3)==6);//true
console.log(add(1)(2)(3)(4)==10);//true

它就像一个无限添加链的魅力!

于 2018-07-13T03:20:39.463 回答
13

试试这个将以两种方式帮助你 add(2)(3) 和 add(2,3)

1.)

 function add(a){ return function (b){return a+b;} }

    add(2)(3) // 5

2.)

function add(a,b){
        var ddd = function (b){return a+b;};
        if(typeof b =='undefined'){
            return ddd;
        }else{
            return ddd(b);
        }
    }

add(2)(3) // 5
add(2,3) // 5
于 2014-12-12T13:25:54.103 回答
12
function add(n) {
  sum = n;
  const proxy = new Proxy(function a () {}, {
    get (obj, key) {
      return () => sum;
    },
    apply (receiver, ...args) {
      sum += args[1][0];
      return proxy;
    },
  });
  return proxy
}

适用于一切,不需要像其他解决方案那样在函数末尾使用 final ()。

console.log(add(1)(2)(3)(10));    // 16
console.log(add(10)(10));         // 20
于 2016-10-14T21:41:59.823 回答
11

ES6 语法使这变得既简单又好:

const add = (a, b) => a + b;

console.log(add(2, 5)); 
// output: 7

const add2 = a => b => a + b;

console.log(add2(2)(5));
// output: 7
于 2016-10-24T19:54:46.043 回答
5

箭头函数无疑使获得所需结果变得非常简单:

const Sum = a => b => b ? Sum( a + b ) : a;

console.log(Sum(3)(4)(2)(5)()); //14

console.log(Sum(3)(4)(1)()); //8
于 2019-02-28T02:07:13.550 回答
4

这是一个通用解决方案,它将解决 add(2,3)()、add(2)(3)() 或任何组合,如 add(2,1,3)(1)(1)(2,3)( 4)(4,1,1)()。请注意,很少有安全检查未完成,可以进一步优化。

function add() {
	var total = 0;

	function sum(){
		if( arguments.length ){
			var arr = Array.prototype.slice.call(arguments).sort();
			total = total + arrayAdder(arr);
			return sum;
		}
		else{
			return total;
		}
	}

	if(arguments.length) {
		var arr1 = Array.prototype.slice.call(arguments).sort();
		var mytotal = arrayAdder(arr1);
		return sum(mytotal);
	}else{
		return sum();
	}

	function arrayAdder(arr){
		var x = 0;
		for (var i = 0; i < arr.length; i++) {
			x = x + arr[i];
		};
		return x;
	}
}
add(2,3)(1)(1)(1,2,3)();

于 2016-01-10T09:04:01.917 回答
4

这将同时处理

add(2,3) // 5

或者

add(2)(3) // 5

这是一个 ES6 咖喱示例...

const add = (a, b) => (b || b === 0) ? a + b : (b) => a + b;
于 2018-05-11T21:15:14.527 回答
3

除了已经说过的,这里有一个通用柯里化的解决方案(基于http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180

Function.prototype.curry = function() {
    if (!arguments.length) return this;
    var __method = this, args = [].slice.call(arguments, 0);
    return function() {
      return __method.apply(this, [].concat(
        [].slice.call(args, 0),
        [].slice.call(arguments, 0)));
   }
}


add = function(x) {
    return (function (x, y) { return x + y }).curry(x)
}

console.log(add(2)(3))
于 2010-02-16T13:55:21.277 回答
3

这是 JS 中的柯里化概念。
您的问题的解决方案是:

function add(a) {
  return function(b) {
    return a + b;
  };
}

这也可以使用箭头函数来实现:

let add = a => b => a + b;

add(1)(2)(5)(4)........(n)()的解决方案;使用递归

function add(a) {
  return function(b){
    return b ? add(a + b) : a;
  }
}

使用ES6 箭头函数语法:

let add = a => b => b ? add(a + b) : a;
于 2020-07-22T06:19:38.790 回答
2

在这种情况下可以使用闭包的概念。
函数“add”返回另一个函数。返回的函数可以访问父作用域中的变量(在本例中为变量 a)。

function add(a){

    return function(b){
        console.log(a + b);
    }

}


add(2)(3);

这是一个了解闭包的链接http://www.w3schools.com/js/js_function_closures.asp

于 2016-05-28T18:13:10.743 回答
2

使用 ES6 扩展...运算符和.reduce函数。使用该变体,您将获得链接语法,但()此处需要最后一次调用,因为始终返回函数:

function add(...args) {
    if (!args.length) return 0;
    const result = args.reduce((accumulator, value) => accumulator + value, 0);
    const sum = (...innerArgs) => {
        if (innerArgs.length === 0) return result;
        return add(...args, ...innerArgs);    
    };
    return sum;
}




// it's just for fiddle output
document.getElementById('output').innerHTML = `
<br><br>add() === 0: ${add() === 0 ? 'true' : 'false, res=' + add()}
<br><br>add(1)(2)() === 3: ${add(1)(2)() === 3 ? 'true' : 'false, res=' + add(1)(2)()}
<br><br>add(1,2)() === 3: ${add(1,2)() === 3 ? 'true' : 'false, res=' + add(1,2)()}
<br><br>add(1)(1,1)() === 3: ${add(1)(1,1)() === 3 ? 'true' : 'false, res=' + add(1)(1,1)()}
<br><br>add(2,3)(1)(1)(1,2,3)() === 13: ${add(2,3)(1)(1)(1,2,3)() === 13 ? 'true' : 'false, res=' + add(2,3)(1)(1)(1,2,3)()}
`;
<div id='output'></div>

于 2017-05-05T15:03:30.163 回答
2
const add = a => b => b ? add(a+b) : a;

console.log(add(1)(2)(3)());

(`${a} ${b}`)用于字符串。

于 2018-01-29T00:14:08.483 回答
1
function add(a, b){
 return a && b ? a+b : function(c){return a+c;}
}

console.log(add(2, 3));
console.log(add(2)(3));
于 2016-08-27T21:40:14.207 回答
1

这个问题已经激发了很多答案,以至于我的“两便士价值”肯定不会破坏事情。

我对尝试使用一些 ES6 表示法将“我最喜欢的”功能(即我想在这样的柯里化函数中找到的那些)组合在一起的众多方法和变体感到惊讶:

const add=(...n)=>{
 const vsum=(a,c)=>a+c;
 n=n.reduce(vsum,0);
 const fn=(...x)=>add(n+x.reduce(vsum,0));
 fn.toString=()=>n; 
 return fn;
}

let w=add(2,1); // = 3
console.log(w()) // 3
console.log(w); // 3
console.log(w(6)(2,3)(4)); // 18
console.log(w(5,3)); // 11
console.log(add(2)-1); // 1
console.log(add()); // 0
console.log(add(5,7,9)(w)); // 24
.as-console-wrapper {max-height:100% !important; top:0%}

基本上,这个递归编程的函数中没有什么是新的。但它确实适用于上述任何答案中提到的所有可能的参数组合,并且最后不需要“空参数列表”。

您可以在所需的任意数量的柯里化级别中使用任意数量的参数,结果将是另一个可用于相同目的的函数。我使用了一个小“技巧”​​来“同时”获得一个数值:我重新定义.toString()了内部函数的功能fn!每当函数在没有参数列表的情况下使用并且“需要一些值”时,Javascript 都会调用此方法。从技术上讲,它是一种“hack”,因为它不会返回一个字符串而是一个数字,但它会以一种在大多数情况下是“期望”的方式工作。试一试!

于 2020-07-23T05:58:19.110 回答
1

也可以试试这个:

let sum = a => b => b ? sum(a + b) :a
console.log(sum(10)(20)(1)(32)())   //63
于 2021-06-30T20:26:25.383 回答
1
const sum  = function (...a) {
    const getSum = d => {
        return d.reduce((i,j)=> i+j, 0);
    };

    a = getSum(a);
    return function (...b) {
        if (b.length) {
            return sum(a + getSum(b)); 
        }
        return a;
    }
};
console.log(sum(1)(2)(3)(4,5)(6)(8)())
于 2021-08-15T17:40:02.147 回答
0

函数 add() { var sum = 0;

    function add() {
        for (var i=0; i<arguments.length; i++) {
            sum += Number(arguments[i]);
        }
        return add;
    }
    add.valueOf = function valueOf(){
        return parseInt(sum);
    };
    return add.apply(null,arguments);
}

// ...

console.log(add() + 0);               // 0
console.log(add(1) + 0);/*                 // 1
console.log(add(1,2) + 0);               // 3
于 2017-09-17T18:07:36.210 回答
0
function A(a){
  return function B(b){
      return a+b;
  }
}

我为这种方法找到了一个很好的解释。它被称为闭包语法

请参考此链接 闭包语法

于 2017-10-11T05:59:46.557 回答
0

我们可以简单地写一个这样的函数

    function sum(x){
      return function(y){
        return function(z){
          return x+y+z;
        }
      }
    }

    sum(2)(3)(4)//Output->9
于 2018-12-18T11:55:28.253 回答
0

不要复杂。

var add = (a)=>(b)=> b ? add(a+b) : a;
console.log(add(2)(3)()); // Output:5

它将在最新的 javascript (ES6) 中工作,这是一个递归函数。

于 2019-07-13T06:34:53.480 回答
0

在这里,我们使用闭包的概念,其中在 main 函数 iter 中调用的所有函数都引用并更新x,因为它们具有闭包。无论循环多长时间,直到最后一个函数,都可以访问x

function iter(x){    
return function innfunc(y){
//if y is not undefined
if(y){
//closure over ancestor's x
x = y+x;
return innfunc;
}
else{
//closure over ancestor's x
return x;
    }
  }
}

iter(2)(3)(4)() //9 iter(1)(3)(4)(5)() //13

于 2019-07-21T16:51:04.770 回答
0

let multi = (a)=>{
	return (b)=>{
		return (c)=>{
			return a*b*c
		}
	}
}
multi (2)(3)(4) //24

let multi = (a)=> (b)=> (c)=> a*b*c;
multi (2)(3)(4) //24

于 2019-09-16T05:28:38.623 回答
0

我们可以使用闭包来完成这项工作。

    function add(param1){
      return function add1(param2){
      return param2 = param1 + param2;
    }
  }
  console.log(add(2)(3));//5
于 2019-11-15T05:47:24.803 回答
0

我想出了一个很好的闭包解决方案,内部函数可以访问父函数的参数访问并存储在其词法范围内,每当我们执行它时,都会得到答案

    const Sum = function (a) {
        return function (b) {
            return b ? Sum(a + b) : a;
        }
    };

    Sum(1)(2)(3)(4)(5)(6)(7)() // result is 28
    Sum(3)(4)(5)() // result is 12
    Sum(12)(10)(20) // result is 42

在此处输入图像描述

于 2019-12-06T09:26:03.917 回答
0

你应该去柯里化以上述格式调用函数。

理想情况下,将两个数字相加的函数就像,

let sum = function(a, b) {
  return a + b;
}

相同的函数可以转换为,

let sum = function(a) {
  return function(b) {
    return a+b;  
  }
}

console.log(sum(2)(3));

让我们了解这是如何工作的。

当您调用 sum(2) 时,它会返回

function(b) {
    return 2 + b;
}

当用 3 进一步调用返回的函数时,b 取值 3。返回结果 5。

更详细的解释:

let sum = function(a) {
  return function(b) {
    return a + b;
  }
}

let func1 = sum(2);
console.log(func1);

let func2 = func1(3)
console.log(func2);

//the same result can be obtained in a single line

let func3 = sum(2)(3);
console.log(func3);

//try comparing the three functions and you will get more clarity.

于 2021-02-05T12:32:36.960 回答
0

以下用例的简单递归解决方案

添加(); // 0

添加(1)(2)();//3

添加(1)(2)(3)();//6

function add(v1, sum = 0) {
     if (!v1) return sum;
      sum += v1
     return (v2) => add(v2, sum);
}
于 2021-05-13T05:42:46.180 回答
-1

function add () {
    var args = Array.prototype.slice.call(arguments);
 
    var fn = function () {
        var arg_fn = Array.prototype.slice.call(arguments);
        return add.apply(null, args.concat(arg_fn));
    }
 
    fn.valueOf = function () {
        return args.reduce(function(a, b) {
            return a + b;
        })
    }
 
    return fn;
}

console.log(add(1));
console.log(add(1)(2));
console.log(add(1)(2)(5));

来自http://www.cnblogs.com/coco1s/p/6509141.html

于 2017-04-28T03:17:31.650 回答
-1
    let add = (a, b) => b === undefined ? add.bind(null, a) : a + b;
    console.log(add(10, 5)); //15
    console.log(add(10)(5)); //15

/* 在返回三元表达式的箭头函数中,我们显式检查第二个参数(b) 是否传入 b==="undefined" 在 add(a,b) 和 add(a)(乙)。

  1. 如果在 add(a)(b) 的情况下为“未定义”,它使用“add.bind(null,a)”,则“bind”方法与创建一个新函数的所有函数相关联(函数是对象)由箭头函数返回并传入:
    • 第一个参数为“null”,“其绑定的上下文允许它默认为窗口对象”
    • "a" 与新函数一起返回的第二个参数。
    • 因此,当此时调用新函数时,add(a)>>>(b) “b”不再未定义,因此三元切换到 a+b。
  2. 如果不是 b==="undefined" 在 add(a, b) 的情况下三元切换到 a+b */
于 2019-12-07T03:25:41.560 回答