我一直在处理JavaScript中的可选参数,如下所示:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  // Do stuff
}

有更好的方法吗?

这样使用||会失败吗?


当前回答

如果您正在使用Undercore库(您应该这样做,这是一个很棒的库):

_.defaults(optionalArg, 'defaultValue');

其他回答

我习惯于看到一些处理可选变量的基本变化。有时,轻松的版本很有用。

function foo(a, b, c) {
  a = a || "default";   // Matches 0, "", null, undefined, NaN, false.
  a || (a = "default"); // Matches 0, "", null, undefined, NaN, false.

  if (b == null) { b = "default"; } // Matches null, undefined.

  if (typeof c === "undefined") { c = "default"; } // Matches undefined.
}

例如,与变量a一起使用的错误默认值在Backbone.js中广泛使用。

我建议您这样使用ArgueJS:

function myFunc(){
  arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'})

  //do stuff, using arguments.requiredArg and arguments.optionalArg
  //    to access your arguments

}

您还可以用期望接收的参数类型替换undefined,如下所示:

function myFunc(){
  arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'})

  //do stuff, using arguments.requiredArg and arguments.optionalArg
  //    to access your arguments

}

在所有optionalArg为false的情况下,您都会得到defaultValue。

function myFunc(requiredArg, optionalArg) {
    optionalArg = optionalArg || 'defaultValue';
    console.log(optionalArg);
    // Do stuff
}
myFunc(requiredArg);
myFunc(requiredArg, null);
myFunc(requiredArg, undefined);
myFunc(requiredArg, "");
myFunc(requiredArg, 0);
myFunc(requiredArg, false);

上述所有日志defaultValue,因为所有6个都是错误的。在情况4、5、6中,您可能不想将optionalArg设置为defaultValue,但它会设置,因为它们是错误的。

对undefined的测试是不必要的,也不像可能的那样健壮,因为正如user568458所指出的,如果通过null或false,则提供的解决方案将失败。API的用户可能认为false或null将强制方法避免该参数。

function PaulDixonSolution(required, optionalArg){
   optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
   console.log(optionalArg);
};
PaulDixonSolution("required");
PaulDixonSolution("required", "provided");
PaulDixonSolution("required", null);
PaulDixonSolution("required", false);

结果是:

defaultValue
provided
null
false

最后两个可能很糟糕。相反,请尝试:

function bulletproof(required, optionalArg){
   optionalArg = optionalArg ? optionalArg : "defaultValue";;
   console.log(optionalArg);
};
bulletproof("required");
bulletproof("required", "provided");
bulletproof("required", null);
bulletproof("required", false);

结果是:

defaultValue
provided
defaultValue
defaultValue

唯一一个不理想的情况是,当您实际拥有布尔值或故意为空的可选参数时。

在ECMAScript 2015(又名“ES6”)中,您可以在函数声明中声明默认参数值:

function myFunc(requiredArg, optionalArg = 'defaultValue') {
    // do stuff
}

关于MDN的更多信息,请参阅本文。

目前只有Firefox支持这一点,但随着标准的完成,预计支持会迅速提高。


编辑(2019-06-12):

默认参数现在被现代浏览器广泛支持。所有版本的Internet Explorer都不支持此功能。然而,Chrome、Firefox和Edge目前都支持它。