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

时间:2011-07-16 11:45:01

标签: javascript

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

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

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

3 个答案:

答案 0 :(得分:146)

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

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

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

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

答案 1 :(得分:25)

ES6更新 - ES6(ES2015 specification)允许default parameters

以下内容在ES6(ES015)环境中运行良好......

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

答案 2 :(得分:4)

您也可以使用ArgueJS

执行此操作
function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

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