Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - 如何在Javascript中声明可选的函数参数? [重复](How can I declare optional function parameters in Javascript? [duplicate])

Possible Duplicate:

(可能重复:)

Can I declare default parameter like

(我可以声明默认参数吗?)

function myFunc( a, b=0) 
{ 
  // b is my optional parameter 
} 

in javascript.

(在javascript中。)

  ask by Uttam Dutta translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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库对可选输入进行一系列检查是很常见的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...