如何在 Javascript 中设置可选参数的默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6717109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:55:06  来源:igfitidea点击:

How do I set the default value for an optional argument in Javascript?

javascript

提问by Royal Pinto

I am writing a Javascript function with an optional argument, and I want to assign the optional argument a default value. How can I assign it a default value?

我正在编写一个带有可选参数的 Javascript 函数,我想为可选参数分配一个默认值。如何为其分配默认值?

I thought it would be this, but it doesn't work:

我以为会是这样,但它不起作用:

function(nodeBox,str = "hai")
{
    // ...
}

回答by mplungjan

If stris null, undefined or 0, this code will set it to "hai"

如果str为 null、undefined 或 0,此代码会将其设置为“hai”

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

如果还需要传0,可以使用:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

回答by sfletche

ES6 Update- ES6 (ES2015 specification) allows for default parameters

ES6 更新- ES6(ES2015 规范)允许默认参数

The following will work just fine in an ES6 (ES015) environment...

以下将在 ES6 (ES015) 环境中正常工作......

function(nodeBox, str="hai")
{
  // ...
}

回答by zVictor

You can also do this with ArgueJS:

你也可以用ArgueJS做到这一点

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}