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

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

我以为会是这样,但没用:

function(nodeBox,str = "hai")
{
// ...
}
102409 次浏览

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";
}
.
.
.

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
}

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

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

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