在 JavaScript 中跳过可选函数参数

发布于 2024-12-19 13:33:13 字数 224 浏览 2 评论 0原文

您能给我指出在 JavaScript 中跳过可选参数的好方法吗?

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

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

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

For example, I want to throw away all opt_ parameters here:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

电影里的梦 2024-12-26 13:33:13

解决方案:

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 中是如何完成此操作的。

Solution:

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

You should use undefined instead of optional parameter you want to skip, because this 100% simulates the default value for optional parameters in 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.

不必你懂 2024-12-26 13:33:13

简短回答

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

如果您发现自己倾向于使用 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"

所以假设一个函数采用它期望的类型的参数“数字”。如果您提供 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. While undefined 也不是 "number" 类型,它的全部工作就是成为一种并非真正类型的类型。这就是为什么它是未初始化变量所采用的值以及函数的默认返回值。

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.

If you find yourself leaning towards using null just because it's shorter, consider declaring a variable named _ as a nice shorthand for 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 undefined evaluates to "undefined"
  • typeof null evaluates to "object"

So suppose a function takes an argument that it expects to be of type "number". If you provide null as a value, you're giving it an "object". The semantics are off.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 undefined as opposed to the classic if (aParam) {...}. You'll be on shaky ground if you continue to use null interchangeably with undefined just because they both happen to coerce to 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):

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 undefined also 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.
黎夕旧梦 2024-12-26 13:33:13

通过使用 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

// Better way!

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

By using 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

// Better way!

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

木落 2024-12-26 13:33:13

只需传递 null 作为参数值。

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

Just pass null as parameter value.

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_timeoutInterval parameter at all)

左岸枫 2024-12-26 13:33:13

还有另一种选项可以避免在每个想要跳过的参数中写入特定的未定义值。在 ES6 中,可以使用 使用数组扩展语法并将其用作函数调用的参数。如果您未指定值,则默认情况下它将被视为 undefined(请考虑到这可能比使用 undefined 值的可读性较差)。

const test = (a = 'A', b = 'B', c = 'C') => {

    console.log(`${a} / ${b} / ${c}`);

};

test();                // A / B / C
test(...[, 'X', 'Y']); // A / X / Y
test(...['X', , 'Y']); // X / B / Y
test(...[, , 'X']);    // A / B / X

出现这种情况是因为:

const array = [ , , , 'A'];

console.log(array); // [undefined, undefined, undefined, 'A']

There is another option that avoids writing specific undefined values in every parameter that one wants to skip. In ES6 one can make use of the Spread syntax with an array and use it as the parameters of the function call. If you don't specify a value, it will be taken as undefined by default (take into account that this could be less readable than using undefined values).

const test = (a = 'A', b = 'B', c = 'C') => {

    console.log(`${a} / ${b} / ${c}`);

};

test();                // A / B / C
test(...[, 'X', 'Y']); // A / X / Y
test(...['X', , 'Y']); // X / B / Y
test(...[, , 'X']);    // A / B / X

And this occurs because:

const array = [ , , , 'A'];

console.log(array); // [undefined, undefined, undefined, 'A']

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文