在JavaScript中跳过可选的函数参数

Dan*_*Dan 53 javascript function-parameter

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

例如,我想抛弃所有opt_参数:

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

Dan*_*Dan 105

解:

goog.net.XhrIo.send(url, undefined, undefined, undefined, {'Cache-Control': 'no-cache'})
Run Code Online (Sandbox Code Playgroud)

您应该使用undefined而不是要跳过的可选参数,因为这100%模拟JavaScript中可选参数的默认值.

小例子:

myfunc(param);

//is equivalent to

myfunc(param, undefined, undefined, undefined);
Run Code Online (Sandbox Code Playgroud)

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


Dou*_*aul 27

简短的回答

最安全的赌注是undefined,并且应该几乎无处不在.但最终,你不能欺骗被调用的函数以为你真正省略了一个参数.

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

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

细节

首先,要知道:

  • typeof undefined 评估为 "undefined"
  • typeof null 评估为 "object"

因此,假设一个函数接受一个它期望为类型的参数"number".如果你提供null一个价值,你就给它一个"object".语义是关闭的.1

随着开发人员继续编写越来越强大的javascript代码,您调用的函数显式检查参数的值的可能性越大,undefined而不是经典if (aParam) {...}.如果你继续null互换使用undefined只是因为他们都碰巧强迫你,你将处于不稳定的状态false.

但请注意,实际上函数可以判断参数是否实际被省略(而不是设置为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
}
Run Code Online (Sandbox Code Playgroud)

脚注

  1. 虽然undefined也不是类型"number",但它的全部工作是成为一种不是真正类型的类型.这就是为什么它是未初始化变量所假定的值,以及函数的默认返回值.


Yur*_*kiy 5

只是null作为参数值传递。

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

  • 您确定要在其中检查`=== undefined`吗? (3认同)
  • 您可以传递 undefined 而不是 null,它更有可能在更多情况下工作,但我不确定是否有一个可以在 _any_ 情况下工作的答案。如果我正在编写一个带有可选参数的函数,我可能会检查 `==null` 以允许 undefined 或 null(除非 null 由于某种原因是合法值),但我可能会检查 `arguments` 对象的长度,并且我已经看到其他使用 `===null` 检查的代码,所以...... (2认同)