在这种模式下执行的Javascript函数“xyz()()”抛出错误? [英] Javascript function executed in this pattern "xyz()()" throws error?
问题描述
var recursiveSum = function(){
console.log(arguments.length);
}
recursiveSum(1)(2)(3);
为什么抛出函数错误?
我使用NodeJs来执行上面的sript。
只有在 recursiveSum
会 return 函数。
现在,您尝试执行 undefined
),并因此引发错误;您尝试执行 undefined(2)(3)
。
您可以这样做。
function currySum(x){return function(y){return函数(z){return x + y + z;
$($ {$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
如果您有可变数量的参数并且想要使用这种curry语法,请查看 Bergi 在评论中提到:这一个,那一个,另一个或此处。
或者,写一个实际的可变参数函数:
function sum(){var s = 0; for(let n of arguments){s + = n; (sum(1,2,3,4)); //总结一个arrayconsole.log中的所有数字(sum.apply(null,[1,2,3,4, ]));
var recursiveSum = function() {
console.log(arguments.length);
}
recursiveSum(1)(2)(3);
Why is it throwing not a function error?
I am using NodeJs to execute above sript.
解决方案 It would only work if recursiveSum
would return a function.
Right now, you try to execute the return value of recursiveSum(1)
as a function. It isn't (it's undefined
), and thus an error is thrown; you try to execute undefined(2)(3)
.
You could do something like this.
function currySum(x) {
return function(y) {
return function(z) {
return x + y + z;
}
}
}
console.log(currySum(1)(2)(3));
If you have a variable number of arguments and want to use this currying syntax, look at any of the questions Bergi mentioned in a comment: this one, that one, another one or here.
Alternatively, write an actual variadic function:
function sum() {
var s = 0;
for (let n of arguments) {
s += n;
}
return s;
}
// summing multiple arguments
console.log(sum(1, 2, 3, 4));
// summing all numbers in an array
console.log(sum.apply(null, [1, 2, 3, 4]));
这篇关于在这种模式下执行的Javascript函数“xyz()()”抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!