具有两个括号和两个参数的JS函数 [英] JS Function With Two Parentheses and Two Params
问题描述
我正在尝试理解一个函数是如何运行的,它使用两个括号和两个参数运行。像这样:
I'm trying to understand how a function works that is run with two parentheses and two parameters. Like so:
add(10)(10); // returns 20
我知道如何编写一个像这样的两个参数:
I know how to write one that takes two params like so:
function add(a, b) {
return a + b;
}
add(10,10); // returns 20
我如何改变该功能,以便可以使用一组参数运行,或两个,并产生相同的结果?
How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?
任何帮助表示赞赏。直截了当地说道。
Any help is appreciated. Literally scratching my head over this.
提前致谢!
推荐答案
我如何改变该功能,以便可以使用一组参数或两个参数运行,并产生相同的结果?
How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?
你可以几乎这样做,但我很难想出一个很好的理由。
You can almost do that, but I'm struggling to think of a good reason to.
这是怎么回事:您检测到您的函数已收到多少参数,如果只收到一个参数,则返回函数而不是数字 —如果被调用,则 函数添加第二个数字:
Here's how: You detect how many arguments your function has received and, if it's received only one, you return a function instead of a number — and have that function add in the second number if it gets called:
function add(a,b) {
if (arguments.length === 1) {
return function(b2) { // You could call this arg `b` as well if you like,
return a + b2; // it would shadow (hide, supercede) the one above
};
}
return a + b;
}
console.log(add(10, 10)); // 20
console.log(add(10)(10)); // 20
我说几乎上面因为 add
函数只收到一个参数,这并不能保证调用者会调用结果。他们可以写:
I said "almost" above because just because the add
function received only one argument, that doesn't guarantee that the caller is going to call the result. They could write:
var x = add(10);
...并且永远不会调用 x $ c $的函数c>现在指的是。
...and never call the function that x
now refers to.
这篇关于具有两个括号和两个参数的JS函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!