在 JavaScript 中,如何创建带有可选参数的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2225877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:19:51  来源:igfitidea点击:

In JavaScript, how can I create a function with an optional parameter?

javascripthtml

提问by SeanD

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:

?在函数声明中使用像 Ruby 这样的标记来表示可选参数是否合适:

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

采纳答案by Damovisa

The first google response I discovered:

我发现的第一个谷歌回复:

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions

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'tuse a question mark in the variable name. Only letters, numbers, $ and _.

其实好像不能在变量名中使用问号。只有字母、数字、$ 和 _。

回答by cletus

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 undefinedso you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:

Javascript 中没有语法指定参数是可选的(或必需的)。所有参数都是可选的。如果未指定它们undefined,则您需要检查它们。例如,此函数实际上将为参数创建默认值 10:

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

Also you can access the parameters programmatically using the argumentsproperty.

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

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

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

回答by JAL

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...
  }

回答by Gilad

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:

注释也可用于指定预期类型。这使您的代码更好,更不容易出错。这是注释的链接:

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

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

回答by nicerobot

First, everyone who writes JavaScript, do yourself a favor and go through Learning Advanced JavaScriptfrom 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 documentingthem well.

只需考虑好好记录它们。

回答by Frank DeRosa

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

回答by Bryan Matthews

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.

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

回答by bobince

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:

不,没有基于语言的方式表示可选参数。不过,我绝对认为值得在评论中指出:

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

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

(注意精确相等测试的三重等号。否则传递的null值也将匹配。您通常希望===在 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++) ...

回答by James

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>

回答by MlleDR

For history sake: You can loop in your arguments with a != nullcheck. For instance :

为了历史起见:您可以通过!= null检查循环您的参数。例如 :

function container(param1, param2, param3, param4){
    var param1, param2, param3, param4 = 0 // or other data types.
    for (var i = 0; i < arguments.length; i++){
       if(i != null) {
       console.log(i); // or put default values to your parameters if you need to.
    }
}

Now, all arguments become optional.

现在,所有参数都变成可选的。