如何确保没有参数传递给函数

How to make sure no arguments are passed to a function

我有一个函数 ab() ,它不带任何参数。如果传递了一个或多个参数,我该如何抛出错误。

function ab(){
    a= 2;
    b=3;
    return a+b;

ab()

现在如果 ab('Hello')

我该如何抛出错误

我试过了:

function ab(){

    if(arguments.length>0) throw 'Cannot pass arguments to this function'
    a= 2;
    b=3;
    return a+b;
}
ab('Hello')

不确定 arguments.length 是否以这种方式工作,还有其他想法吗?

您可以像这样使用 JS spread operator (...):

虽然你的版本应该也可以工作

此外,正如@Barmar 所说,“这还有一个额外的好处,它也适用于箭头函数。

function my_function(...args) {
  if(args.length) throw "Args cannot be passed";
  console.log("No args are present");
}


my_function("Hello");