我正在编写带有可选参数的Javascript函数,我想为可选参数分配一个默认值.如何为其指定默认值?
我以为会是这样,但它不起作用:
function(nodeBox,str = "hai")
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
mpl*_*jan 152
如果str为null,undefined或0,则此代码将其设置为"hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
Run Code Online (Sandbox Code Playgroud)
如果你还需要传递0,你可以使用:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
Run Code Online (Sandbox Code Playgroud)
sfl*_*che 26
以下将在ES6(ES015)环境中正常工作......
function(nodeBox, str="hai")
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用ArgueJS执行此操作:
function (){
arguments = __({nodebox: undefined, str: [String: "hai"]})
// and now on, you can access your arguments by
// arguments.nodebox and arguments.str
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93419 次 |
| 最近记录: |