在JavaScript中,如何使用可选参数创建函数?

Sea*_*anD 26 html javascript

问题:在JavaScript中定义带有可选参数的函数的正确方法是什么?

例如:

function myFunc(optionVar1) {
    if(optionVar1 == undefined) {
        ...
    } else {
        ...
    }
}

myFunc('10');  // valid function call
myFunc();      // also a valid function call
Run Code Online (Sandbox Code Playgroud)

?在函数声明中使用像Ruby这样的标记是否合适,以表示可选参数:

function myFunc(optionVar1?) {...}  //  <--- notice the ? mark
Run Code Online (Sandbox Code Playgroud)

cle*_*tus 60

Javascript中没有语法指定参数是可选的(或必需的).所有参数都是可选的.如果没有指定它们,undefined那么你需要检查它.例如,此函数实际上会为参数创建默认值10:

function myfunc(someParam) {
  if (someParam === undefined) {
    someParam = 10;
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用该arguments属性以编程方式访问参数.

最后,如果你有超过3-4个参数,通常建议使用匿名对象.

  • 这可以简化为ES6`function myfunc(someParam = 10){All code =}} (3认同)

JAL*_*JAL 6

实际上,JS函数中的所有参数都是可选的.如果省略参数,则没有警告或错误.

您可以设置默认值

function throw_cat(dist){
  dist = typeof dist=='undefined' ? 20 : dist;
   //OR
  dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default
  //etc...
  }
Run Code Online (Sandbox Code Playgroud)


Dam*_*isa 1

我发现的第一个谷歌回复:

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions

我还没有看到任何使用问号来提醒调用者可选参数的实例。虽然它在其他语言中已经完成,但我认为在 javascript 中没有必要。

事实上,变量名中似乎不能使用问号。仅限字母、数字、$ 和 _。