With ES6: This is now part of the language :
(使用ES6:现在这是语言的一部分 :)
function myFunc(a, b = 0) {
// function body
}
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).
(请记住,ES6检查undefined
的值而不是truthy-ness(因此只有真正的未定义值才能获得默认值 - 像null这样的假值不会默认值)。)
With ES5:
(使用ES5:)
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}
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, ''
(根据MiniGod的评论不是真正的值: null, undefined, 0, false, ''
)
It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.
(在函数实际启动之前,看到JavaScript库对可选输入进行一系列检查是很常见的。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…