开发者

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

开发者 https://www.devze.com 2023-03-20 14:15 出处:网络
This question already has answers here: Set a default开发者_JS百科 parameter value for a JavaScript function
This question already has answers here: Set a default开发者_JS百科 parameter value for a JavaScript function (29 answers) Closed 6 years ago.

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?

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

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


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

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

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

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


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

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

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


You can also do this with ArgueJS:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号