我有一个测验,询问以下问题,但我不确定是否可以在Javascript函数上传递多个变量:
编写一个名为“MultiplyBy”的函数,在调用时会产生以下输出:
console.log(mul(2)(3)(4)); // output : 24
console.log(mul(4)(3)(4)); // output : 48
答案 0 :(得分:3)
您可以在每次通话时返回功能。此技术的名称为currying。
// For three chained calls
function mul(i) {
return function(j) {
return function(k) {
return i * j * k;
}
}
}
console.log('result: ' + mul(2)(3)(4)); // output : 24
console.log('result: ' + mul(4)(3)(4)); // output : 48
// For an arbitrary number of chained calls, must resort to .toString
function mulN(i) {
var m = (j) => mulN(i * j);
m.toString = () => ''+i;
m.valueOf = () => i; // call .valueOf() at any point to get the current val
return m;
}
console.log('result: ' + mulN(2));
console.log('result: ' + mulN(2)(3));
console.log('result: ' + mulN(2)(3)(4));
console.log('result: ' + mulN(2)(3)(4)(5));
console.log('result: ' + (mulN(2)(3)(4)(5) == 120)); // true because of .valueOf