在JavaScript中,如何使用可选参数创建函数?

时间:2021-02-28 11:10:10

Question: What is the proper way to define a function in JavaScript that takes optional parameters?

问:在JavaScript中定义具有可选参数的函数的正确方法是什么?

For example:

例如:

function myFunc(optionVar1) {
    if(optionVar1 == undefined) {
        ...
    } else {
        ...
    }
}

myFunc('10');  // valid function call
myFunc();      // also a valid function call

Is it proper to use a ? mark like Ruby in the function declaration like so to denote optional parameters:

使用a合适吗?在函数声明中标记如Ruby,表示可选参数:

function myFunc(optionVar1?) {...}  //  <--- notice the ? mark

9 个解决方案

#1


2  

The first google response I discovered:

我发现的第一个谷歌响应:

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions (link is broken)

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions(链接坏了)

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.

我还没有见过任何用问号提醒调用者使用可选参数的情况。虽然它是用其他语言完成的,但我认为它在javascript中没有必要。

In fact, it seems that you can't use a question mark in the variable name. Only letters, numbers, $ and _.

事实上,似乎您不能在变量名中使用问号。只有字母、数字、$和_。

#2


55  

There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren't specified they're undefined so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:

Javascript中没有语法指定参数是可选的(或必需的)。所有参数都是可选的。如果它们没有被指定,它们是未定义的,所以需要检查一下。例如,这个函数实际上会为参数创建一个默认值10:

function myfunc(someParam) {
  if (someParam === undefined) {
    someParam = 10;
  }
  ...
}

Also you can access the parameters programmatically using the arguments property.

还可以使用arguments属性以编程方式访问参数。

Lastly, if you have more than about 3-4 parameters it's generally advisable to use an anonymous object instead.

最后,如果您有超过3-4个参数,通常建议使用匿名对象。

#3


7  

Actually, all parameters are optional in JS functions. There is no warning or error if you omit a parameter.

实际上,JS函数中的所有参数都是可选的。如果省略了一个参数,则没有任何警告或错误。

You can set defaults like

可以设置默认值。

function throw_cat(dist){
  dist = typeof dist=='undefined' ? 20 : dist;
   //OR
  dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default
  //etc...
  }

#4


3  

First, everyone who writes JavaScript, do yourself a favor and go through Learning Advanced JavaScript from John Resig.

首先,每个编写JavaScript的人都要帮自己一个忙,从John Resig那里学习高级JavaScript。

function myFunc(arg1, arg2 /* varargs... */) {
  var optional = Array.prototype.slice.call( arguments, 2 );

Every parameter to a function is "optional", even those you declare in the parameter list of the function declaration.

函数的每个参数都是“可选的”,即使是在函数声明的参数列表中声明的参数。

Just consider documenting them well.

只要把它们记录好就行了。

#5


3  

You can use annotation such as {Object=} or {number=} in the comment section when using a doclet:

当您使用doclet时,可以在注释部分使用诸如{Object=}或{number=}之类的注释:

/** 
 * @param {object=}xyz
 */ 

Modern IDE knows to recognize annotations for JavaScript and shows you indications about potential problems in your code.

现代IDE知道如何识别JavaScript的注释,并显示代码中潜在问题的提示。

Example:

例子:

/**
 *
 * @param query 
 * @param callback 
 * @param {number=} ttl optional time-to-leave
 */
 loadByJSONP:function loadByJSONP(query, callback, ttl) {
   ...do some work
 }

In this example 'ttl' is optional. the annotation {number=} indicate to IDE that this parameter is optional. Accordingly when you call this function with two parameters only, you will not get warning.

在这个示例中,“ttl”是可选的。注释{number=}向IDE表明此参数是可选的。因此,当您仅用两个参数调用这个函数时,您将不会得到警告。

Annotations can also be used for designating the expected type. this makes your code better and less prone to bugs. Here is the link for annotations:

注解也可以用来指定预期的类型。这使您的代码更好,更不容易出现bug。下面是注解的链接:

https://developers.google.com/closure/compiler/docs/js-for-compiler

https://developers.google.com/closure/compiler/docs/js-for-compiler

#6


2  

Some sources will tell you to skip parameters altogether and instead make use of the arguments array. This lets you take any input that's provided to your function, and you can decide how to respond to the arguments passed to your function as you see fit.

一些源将告诉您完全跳过参数,而是使用参数数组。这使您可以接受为函数提供的任何输入,并可以决定如何响应传递给函数的参数。

You can read more about it here: http://www.devguru.org/technologies/ecmascript/quickref/arguments.html

你可以在这里阅读更多:http://www.devguru.org/technologies/ecmascript/quickref/arguments.html

#7


2  

cletus and Damovisa have made good suggestions. I would also add that some (like myself) might prefer a notation like this:

cletus和Damovisa提出了很好的建议。我还想说一些(像我自己)可能喜欢这样的符号:

function foo(/*bar*/) {
   if (arguments.length == 1) {
      var bar = arguments[0];
      ...
   }
}

This serves to document to developers of your code base that the argument is optional and also documents the name, but it also prevents the argument from showing up in the function name in a debugger (the example would show up as foo() rather than foo(optional_argument). Otherwise, developers who are consuming the API might assume that it was required.

这可以向代码库的开发人员证明,参数是可选的,也可以记录名称,但是它也可以防止参数在调试器中出现在函数名中(这个示例将显示为foo()而不是foo(optional_argument)。否则,使用API的开发人员可能会认为它是必需的。

Edit: This is especially useful for optional arguments that are intended to be used internally.

编辑:这对于要在内部使用的可选参数特别有用。

#8


1  

Just don't define the function with any parameters and access the special arguments array from within the function where you want the optional parameters to be. Example below.

只是不要用任何参数定义函数并从函数中访问您想要的可选参数的特殊参数数组。下面的例子。

<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
function foo() {
  var argv = foo.arguments;
  var argc = argv.length;
  for (var i = 0; i < argc; i++) {
    alert("Argument " + i + " = " + argv[i]);
   }
}
</SCRIPT>
</HEAD>
<BODY onload="foo('hello', 'world');">
</BODY>
</HTML>

#9


1  

Is it proper to use a ? mark like Ruby in the function declaration

使用a合适吗?在函数声明中像Ruby那样标记

No, there's no language-based way denote an optional arg. I definitely think it's worth indicating in a comment, though:

不,没有基于语言的方法来表示可选的arg。不过,我绝对认为有必要在评论中指出:

function myFunc(var1, var2 /* optional */, var3 /* optional */) {
    if (var2===undefined) ...

(Note the triple-equals for exact equality testing. Otherwise a passed null value will also match. You generally want === for most comparisons in JS, as the double-equals is undesirably weakly-typed.)

(请注意“三等于”是为了进行精确的平等测试。否则,传递的空值也将匹配。您通常想要===在JS中进行大多数比较,因为双等号是不可取的弱类型。

For when you've got an indeterminate number of optional arguments, you generally omit them from the function statement, and again a comment is polite:

因为当你有不确定数量的可选参数时,你通常会在函数语句中省略它们,而且评论也是礼貌的:

function myFunc(var1 /* , optional var2..varN */) {
    for (var i= 1; i<arguments.length; i++) ...

#1


2  

The first google response I discovered:

我发现的第一个谷歌响应:

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions (link is broken)

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions(链接坏了)

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.

我还没有见过任何用问号提醒调用者使用可选参数的情况。虽然它是用其他语言完成的,但我认为它在javascript中没有必要。

In fact, it seems that you can't use a question mark in the variable name. Only letters, numbers, $ and _.

事实上,似乎您不能在变量名中使用问号。只有字母、数字、$和_。

#2


55  

There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren't specified they're undefined so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:

Javascript中没有语法指定参数是可选的(或必需的)。所有参数都是可选的。如果它们没有被指定,它们是未定义的,所以需要检查一下。例如,这个函数实际上会为参数创建一个默认值10:

function myfunc(someParam) {
  if (someParam === undefined) {
    someParam = 10;
  }
  ...
}

Also you can access the parameters programmatically using the arguments property.

还可以使用arguments属性以编程方式访问参数。

Lastly, if you have more than about 3-4 parameters it's generally advisable to use an anonymous object instead.

最后,如果您有超过3-4个参数,通常建议使用匿名对象。

#3


7  

Actually, all parameters are optional in JS functions. There is no warning or error if you omit a parameter.

实际上,JS函数中的所有参数都是可选的。如果省略了一个参数,则没有任何警告或错误。

You can set defaults like

可以设置默认值。

function throw_cat(dist){
  dist = typeof dist=='undefined' ? 20 : dist;
   //OR
  dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default
  //etc...
  }

#4


3  

First, everyone who writes JavaScript, do yourself a favor and go through Learning Advanced JavaScript from John Resig.

首先,每个编写JavaScript的人都要帮自己一个忙,从John Resig那里学习高级JavaScript。

function myFunc(arg1, arg2 /* varargs... */) {
  var optional = Array.prototype.slice.call( arguments, 2 );

Every parameter to a function is "optional", even those you declare in the parameter list of the function declaration.

函数的每个参数都是“可选的”,即使是在函数声明的参数列表中声明的参数。

Just consider documenting them well.

只要把它们记录好就行了。

#5


3  

You can use annotation such as {Object=} or {number=} in the comment section when using a doclet:

当您使用doclet时,可以在注释部分使用诸如{Object=}或{number=}之类的注释:

/** 
 * @param {object=}xyz
 */ 

Modern IDE knows to recognize annotations for JavaScript and shows you indications about potential problems in your code.

现代IDE知道如何识别JavaScript的注释,并显示代码中潜在问题的提示。

Example:

例子:

/**
 *
 * @param query 
 * @param callback 
 * @param {number=} ttl optional time-to-leave
 */
 loadByJSONP:function loadByJSONP(query, callback, ttl) {
   ...do some work
 }

In this example 'ttl' is optional. the annotation {number=} indicate to IDE that this parameter is optional. Accordingly when you call this function with two parameters only, you will not get warning.

在这个示例中,“ttl”是可选的。注释{number=}向IDE表明此参数是可选的。因此,当您仅用两个参数调用这个函数时,您将不会得到警告。

Annotations can also be used for designating the expected type. this makes your code better and less prone to bugs. Here is the link for annotations:

注解也可以用来指定预期的类型。这使您的代码更好,更不容易出现bug。下面是注解的链接:

https://developers.google.com/closure/compiler/docs/js-for-compiler

https://developers.google.com/closure/compiler/docs/js-for-compiler

#6


2  

Some sources will tell you to skip parameters altogether and instead make use of the arguments array. This lets you take any input that's provided to your function, and you can decide how to respond to the arguments passed to your function as you see fit.

一些源将告诉您完全跳过参数,而是使用参数数组。这使您可以接受为函数提供的任何输入,并可以决定如何响应传递给函数的参数。

You can read more about it here: http://www.devguru.org/technologies/ecmascript/quickref/arguments.html

你可以在这里阅读更多:http://www.devguru.org/technologies/ecmascript/quickref/arguments.html

#7


2  

cletus and Damovisa have made good suggestions. I would also add that some (like myself) might prefer a notation like this:

cletus和Damovisa提出了很好的建议。我还想说一些(像我自己)可能喜欢这样的符号:

function foo(/*bar*/) {
   if (arguments.length == 1) {
      var bar = arguments[0];
      ...
   }
}

This serves to document to developers of your code base that the argument is optional and also documents the name, but it also prevents the argument from showing up in the function name in a debugger (the example would show up as foo() rather than foo(optional_argument). Otherwise, developers who are consuming the API might assume that it was required.

这可以向代码库的开发人员证明,参数是可选的,也可以记录名称,但是它也可以防止参数在调试器中出现在函数名中(这个示例将显示为foo()而不是foo(optional_argument)。否则,使用API的开发人员可能会认为它是必需的。

Edit: This is especially useful for optional arguments that are intended to be used internally.

编辑:这对于要在内部使用的可选参数特别有用。

#8


1  

Just don't define the function with any parameters and access the special arguments array from within the function where you want the optional parameters to be. Example below.

只是不要用任何参数定义函数并从函数中访问您想要的可选参数的特殊参数数组。下面的例子。

<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
function foo() {
  var argv = foo.arguments;
  var argc = argv.length;
  for (var i = 0; i < argc; i++) {
    alert("Argument " + i + " = " + argv[i]);
   }
}
</SCRIPT>
</HEAD>
<BODY onload="foo('hello', 'world');">
</BODY>
</HTML>

#9


1  

Is it proper to use a ? mark like Ruby in the function declaration

使用a合适吗?在函数声明中像Ruby那样标记

No, there's no language-based way denote an optional arg. I definitely think it's worth indicating in a comment, though:

不,没有基于语言的方法来表示可选的arg。不过,我绝对认为有必要在评论中指出:

function myFunc(var1, var2 /* optional */, var3 /* optional */) {
    if (var2===undefined) ...

(Note the triple-equals for exact equality testing. Otherwise a passed null value will also match. You generally want === for most comparisons in JS, as the double-equals is undesirably weakly-typed.)

(请注意“三等于”是为了进行精确的平等测试。否则,传递的空值也将匹配。您通常想要===在JS中进行大多数比较,因为双等号是不可取的弱类型。

For when you've got an indeterminate number of optional arguments, you generally omit them from the function statement, and again a comment is polite:

因为当你有不确定数量的可选参数时,你通常会在函数语句中省略它们,而且评论也是礼貌的:

function myFunc(var1 /* , optional var2..varN */) {
    for (var i= 1; i<arguments.length; i++) ...