在 JavaScript 中,如何创建带有可选参数的函数? [英] In JavaScript, how can I create a function with an optional parameter?
问题描述
问题:在 JavaScript 中定义带有可选参数的函数的正确方法是什么?
Question: What is the proper way to define a function in JavaScript that takes optional parameters?
例如:
function myFunc(optionVar1) {
if(optionVar1 == undefined) {
...
} else {
...
}
}
myFunc('10'); // valid function call
myFunc(); // also a valid function call
在函数声明中像 Ruby 一样使用 ?
标记来表示可选参数是否合适:
Is it proper to use a ?
mark like Ruby in the function declaration like so to denote optional parameters:
function myFunc(optionVar1?) {...} // <--- notice the ? mark
推荐答案
我发现的第一个 google 响应:
The first google response I discovered:
http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions
我还没有看到任何使用问号来提醒调用者注意可选参数的情况.虽然它在其他语言中完成,但我认为在 javascript 中没有必要.
I haven't seen any instances where a question mark is used to alert a caller to an optional parameter. While it's done in other languages, I don't think it's necessary in javascript.
事实上,看来你不能 在变量名中使用问号.只有字母、数字、$ 和 _.
In fact, it seems that you can't use a question mark in the variable name. Only letters, numbers, $ and _.
这篇关于在 JavaScript 中,如何创建带有可选参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!