如何在Javascript中声明可选的函数参数? [英] How can I declare optional function parameters in Javascript?
问题描述
我可以声明默认参数,如
Can I declare default parameter like
function myFunc( a, b=0)
{
// b is my optional parameter
}
在javascript中。
in javascript.
推荐答案
使用ES6:现在这是语言的一部分:
function myFunc(a, b = 0) {
// function body
}
请记住,ES6会根据 undefined
检查值,而不是针对truthy-ness(所以只有真正的叔叔罚款值获得默认值 - 像null这样的假值不会默认值。)
Please keep in mind that ES6 checks the values against undefined
and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).
使用ES5:
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}
只要您明确传入的所有值都是 truthy 。
根据MiniGod的评论不符合规定的值: null,undefined,0,false,''
This works as long as all values you explicitly pass in are truthy.
Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''
在函数实际启动之前,看到JavaScript库对可选输入进行一系列检查是很常见的。
It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.
这篇关于如何在Javascript中声明可选的函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!