跳过 JavaScript 中的可选函数参数

新手上路,请多包涵

你能告诉我在 JavaScript 中跳过可选参数的好方法吗?

例如,我想在这里丢弃所有 opt_ 参数:

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

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

解决方案:

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

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

小例子:

 myfunc(param);

//is equivalent to

myfunc(param, undefined, undefined, undefined);

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

原文由 Dan 发布,翻译遵循 CC BY-SA 3.0 许可协议

简答

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

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

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

细节

首先,要知道:

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

因此,假设一个函数接受一个它期望类型为 "number" 的参数。如果您提供 null 作为一个值,您将给它一个 "object" 。语义关闭。 1个

随着开发人员继续编写越来越健壮的 javascript 代码,您调用的函数越来越有可能明确检查 undefined 的参数值,而不是经典的 if (aParam) {...} 。如果你继续使用 nullundefined 互换使用,你将处于不稳定的状态,只是因为它们都恰好强制为 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
}


脚注

  1. 虽然 undefined 也不是类型 "number" ,但它的全部工作是成为一个实际上不是类型的类型。这就是为什么它是未初始化变量假定的值,也是函数的默认返回值。

原文由 Doug Paul 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏