【问题标题】:Javascript function executed in this pattern "xyz()()" throws error?以这种模式“xyz()()”执行的 Javascript 函数抛出错误?
【发布时间】:2017-07-13 05:16:45
【问题描述】:
 var recursiveSum = function() {
    console.log(arguments.length);
 }
 recursiveSum(1)(2)(3);

为什么不抛出函数错误? 我正在使用 NodeJs 执行上面的脚本。

【问题讨论】:

标签: javascript function


【解决方案1】:

只有当recursiveSumreturn 用作函数时,它才会起作用。

现在,您尝试将recursiveSum(1) 的返回值作为函数执行。不是(它是undefined),因此会引发错误;你尝试执行undefined(2)(3)

你可以这样做。

function currySum(x) {
  return function(y) {
    return function(z) {
      return x + y + z;
    }
  }
}

console.log(currySum(1)(2)(3));

如果您有可变数量的参数并想使用这种柯里化语法,请查看comment 中提到的任何问题Bergithis onethat oneanother onehere .


或者,写一个实际的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]));

【讨论】:

  • 如果我有 20 个参数怎么办
  • 我已经编辑了我的答案来解决这种情况,Sourabh。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多