繁体   English   中英

Node.js函数中的可选参数

[英]Optional arguments in nodejs functions

创建在Node.js中使用可选参数的函数的最佳方法是什么?

例如我知道这种方法:

    function optionalArguments(a,b){
        var a = a || "nothing";
        var b = b || "nothing";
    } 

但是在这种情况下,如果我这样做:

optionalArguments(false,false)

尽管我已经传递了一个参数,但a和b都返回“ nothing”。

当我这样调用函数时,也会出现意外的令牌错误

optionalArguments(,“ xxx”);

有没有更好的或标准的方法来处理nodejs中的可选参数?

任何帮助表示赞赏。 提前致谢。

如果您使用的是Node.js v6(或更高版本),则可以访问默认参数。

function optionalArguments(a="nothing", b="nothing") {
  return `a: ${a}, b: ${b}`;
}

然后

optionalArguments(false, false)     // 'a: false, b: false'
optionalArguments('this')           // 'a: this, b: nothing'
optionalArguments()                 // 'a: nothing, b: nothing'
optionalArguments(undefined,'that') // 'a: nothing, b: that'

您这样做完全像客户端javascript。

您建议的方法确实有效,但是,正如您所注意到的,当可以省略的参数不是最后一个参数时,这很痛苦。

在这种情况下,通常使用的是“选项”对象:

function optionalArguments(options){
    var a = options.a || "nothing";
    var b = options.b || "nothing";
}

请注意|| 是危险的。 如果要设置诸如false""0NaNnull ,则必须这样做:

function optionalArguments(options){
    var a = options.a !== undefined ? options.a : "nothing";
    var b = options.b !== undefined ? options.b : "nothing";
}

如果您经常这样做,实用程序功能可能会很方便:

function opt(options, name, default){
     return options && options[name]!==undefined ? options[name] : default;
}

function optionalArguments(options){
    var a = opt(options, 'a', "nothing");
    var b = opt(options, 'b', "nothing");
}

这样,您甚至可以使用

optionalArguments();

|| 只是普通的老人或操作员。 当期望该值不为假时,它将派上用场。 但是,如果像0falsenull是有效且期望的,则需要采用其他方法。

== null

要检查是否传递了非null值,请使用== null 当传入nullundefined时,它将返回true

function optionalArguments (a, b) {
    a = a == null ? "nothing" : a;
    b = b == null ? "nothing" : b;
    ...
}

在大多数情况下,这是实现可选参数的最佳方法。 当需要默认值时,它允许调用方传递null 当调用者想为第二个参数传递值,但为第一个参数使用默认值时,此功能特别有用。 例如, optionalArguments(null, 22)

=== undefined

如果null是有效的期望值,则使用undefined===运算符进行上述比较。 确保您使用有效的undefined值进行比较。 脚本可能会说var undefined = 0 ,给您带来无尽的麻烦。 您始终可以=== void 0来测试undefined

arguments.length

如果我这样调用您的函数怎么办?

optionalArguments("something", void 0);

在这种情况下,我确实传递了一个值,但是该值是undefined 有时您确实想检测是否传入了参数。 在这种情况下,您需要检查arguments.length

function optionalArguments (a, b) {
    a = arguments.length > 0 ? a : "nothing";
    b = arguments.length > 1 ? b : "nothing";
    ...
}

作为使用默认参数并且仍然能够使用false值的一种简便方法,您可以这样做

function optionalArguments(a, b){
  a = typeof a !== 'undefined' ? a : "nothing"; 
  b = typeof b !== 'undefined' ? b : "nothing";
} 

另请参阅有关此问题的替代选项

无论您选择哪个选项, optionalArguments(, "xxx")都将无效,因为缺少的参数使语法无效:无法解析代码。 要修复它,您可以使用

optionalArguments(undefined, "xxx");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM