raj*_*kvk 38 javascript currying
我想使这种语法成为可能:
var a = add(2)(3); //5
Run Code Online (Sandbox Code Playgroud)
根据我在http://dmitry.baranovskiy.com/post/31797647上读到的内容
我不知道如何使它成为可能.
tva*_*son 86
您需要添加为一个函数,该函数接受一个参数并返回一个函数,该函数接受一个参数,该参数将参数添加到add及其自身.
var add = function(x) {
return function(y) { return x + y; };
}
Run Code Online (Sandbox Code Playgroud)
Osc*_*hed 34
function add(x) {
return function(y) {
return x + y;
};
}
Run Code Online (Sandbox Code Playgroud)
啊,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
Run Code Online (Sandbox Code Playgroud)
NVI*_*NVI 15
function add(x){
return function(y){
return x+y
}
}
Run Code Online (Sandbox Code Playgroud)
小智 11
试试这会帮助你以两种方式添加(2)(3)和添加(2,3)
1.)
function add(a){ return function (b){return a+b;} }
add(2)(3) // 5
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Ben*_*dez 10
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
}
Run Code Online (Sandbox Code Playgroud)
适用于所有内容,并且不需要函数末尾的final(),就像其他解决方案一样.
console.log(add(1)(2)(3)(10)); // 16
console.log(add(10)(10)); // 20
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这是关于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
Run Code Online (Sandbox Code Playgroud)
它就像一个无限添加链的魅力!
箭头函数无疑使获得所需结果变得非常简单:
const Sum = a => b => b ? Sum( a + b ) : a;
console.log(Sum(3)(4)(2)(5)()); //14
console.log(Sum(3)(4)(1)()); //8
Run Code Online (Sandbox Code Playgroud)