gpt4 book ai didi

函数中的 JavaScript 参数

转载 作者:行者123 更新时间:2023-11-28 17:33:54 24 4
gpt4 key购买 nike

我有一个测验询问以下问题,但我不太确定是否可以在 Javascript 函数上传递多个变量:

编写一个名为“MultiplyBy”的函数,该函数在调用时将产生以下输出:

console.log(mul(2)(3)(4)); // output : 24 
console.log(mul(4)(3)(4)); // output : 48

最佳答案

您可以在每次调用时返回函数。该技术的名称是 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

关于函数中的 JavaScript 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49602878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com