在这种模式下执行的Javascript函数“xyz()()”抛出错误? [英] Javascript function executed in this pattern "xyz()()" throws error?

查看:127
本文介绍了在这种模式下执行的Javascript函数“xyz()()”抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var recursiveSum = function(){
console.log(arguments.length);
}
recursiveSum(1)(2)(3);

为什么抛出函数错误?
我使用NodeJs来执行上面的sript。

解决方案

只有在 recursiveSum return 函数。

现在,您尝试执行 recursiveSum(1)作为函数的返回值。它不是(它是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆