跳过 JavaScript 中的可选函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8356227/
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-24 05:39:55  来源:igfitidea点击:

Skipping optional function parameters in JavaScript

javascriptfunction-parameter

提问by Dan

Could you please point me to the nice way of skipping optional parameters in JavaScript.

能否请您指出在 JavaScript 中跳过可选参数的好方法。

For example, I want to throw away all opt_parameters here:

例如,我想在opt_这里扔掉所有参数:

goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content, {'Cache-Control': 'no-cache'}, opt_timeoutInterval)

回答by Dan

Solution:

解决方案:

goog.net.XhrIo.send(url, undefined, undefined, undefined, {'Cache-Control': 'no-cache'})

You should use undefinedinstead of optional parameter you want to skip, because this 100% simulates the default value for optional parameters in JavaScript.

您应该使用undefined代替要跳过的可选参数,因为这 100% 模拟了 JavaScript 中可选参数的默认值。

Small example:

小例子:

myfunc(param);

//is equivalent to

myfunc(param, undefined, undefined, undefined);

Strong recommendation: use JSON if you have a lot of parameters, and you can have optional parameters in the middle of the parameters list. Look how this is done in jQuery.

强烈建议:如果参数很多,就使用JSON,参数列表中间可以有可选参数。看看这是如何在jQuery 中完成的。

回答by Doug Paul

Short answer

简答

The safest bet is undefined, and should work almost ubiquitously. Ultimately, though, you cannot trick the function being called into thinking you truly omitted a parameter.

最安全的选择是undefined,并且应该几乎无处不在。但是,最终,您不能欺骗被调用的函数,以为您确实省略了参数。

If you find yourself leaning towards using nulljust because it's shorter, consider declaring a variable named _as a nice shorthand for undefined:

如果您发现自己null仅仅因为它更短而倾向于使用,请考虑声明一个名为 的变量,_作为 的一个很好的简写undefined

(function() { // First line of every script file
    "use strict";
    var _ = undefined; // For shorthand
    // ...
    aFunction(a, _, c);
    // ...
})(); // Last line of every script

Details

细节

First, know that:

首先要知道:

  • typeof undefinedevaluates to "undefined"
  • typeof nullevaluates to "object"
  • typeof undefined评估为 "undefined"
  • typeof null评估为 "object"

So suppose a function takes an argument that it expects to be of type "number". If you provide nullas a value, you're giving it an "object". The semantics are off.1

所以假设一个函数接受一个它期望类型为 的参数"number"。如果你提供null一个值,你会给它一个"object". 语义关闭。1

As developers continue to write increasingly robust javascript code, there's an increasing chance that the functions you call explicitly check a parameter's value for undefinedas opposed to the classic if (aParam) {...}. You'll be on shaky ground if you continue to use nullinterchangeably with undefinedjust because they both happen to coerce to false.

随着开发人员继续编写越来越健壮的 javascript 代码,您调用的函数显式检查参数值的可能性越来越大,undefined而不是经典的if (aParam) {...}. 如果您继续null交替使用和undefined仅仅因为它们都碰巧强制使用false.

Be aware, though, that it is in fact possible for a function to tell if a parameter was actually omitted (versus being set to undefined):

但请注意,实际上函数可以判断参数是否被实际省略(相对于设置为undefined):

f(undefined); // Second param omitted
function f(a, b) {
    // Both a and b will evaluate to undefined when used in an expression
    console.log(a); // undefined
    console.log(b); // undefined
    // But...
    console.log("0" in arguments); // true
    console.log("1" in arguments); // false
}


Footnotes

脚注

  1. While undefinedalso isn't of type "number", it's whole job is to be a type that isn't really a type. That's why it's the value assumed by uninitialized variables, and the default return value for functions.
  1. 虽然undefined也不是 type "number",但它的全部工作是成为一个不是真正类型的类型。这就是为什么它是未初始化变量假定的值,以及函数的默认返回值。

回答by Yuriy Rozhovetskiy

Just pass nullas parameter value.

只需null作为参数值传递。

Added: you also can skip all consequent optional parameters after the last that you want to pass real value (in this case you may skip opt_timeoutIntervalparameter at all)

补充:您还可以跳过最后一个要传递实际值的后续可选参数(在这种情况下,您可以完全跳过opt_timeoutInterval参数)