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

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

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

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

只需将 null作为参数值传递。

新增: 你也可以跳过所有后续的可选参数后,你想传递真实值(在这种情况下,你可以跳过 opt_timeoutInterval参数在所有)

解决方案:

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是怎么做的。

长话短说

最安全的选择是 undefined,几乎无处不在。但是,最终,您不能欺骗被调用的函数,让它认为您确实省略了一个参数。

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

(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 代码,与经典的 if (aParam) {...}相比,您调用的函数显式检查 undefined参数值的可能性越来越大。如果你继续使用 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"类型,但它的整个工作就是成为一个不是真正的类型的类型。这就是为什么它是未初始化变量所假定的值,以及函数的默认返回值。

通过使用 ES6 javascript!

function myfunc(x=1,y=2,z=6){
console.log(x);
console.log(y);
console.log(z);
}
myfunc(5) //Output: 5 2 6
myfunc(3,undefined,8) //Output: 3 2 8

更好的办法!

 function myfunc(x=1,y=2,z=6){
console.log(x);
console.log(y);
console.log(z);
}
// skip y argument using: ...[,] and it's mean to undefine
// 1 argument for ...[,] 2 arguments for ...[,,] and so on.....
myfunc(7, ...[,], 4); //Output: 7 2 4