javascript JS:函数参数默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4771330/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS: functions arguments default values
提问by SaltLake
In some languages you can set default values for function's arguments:
在某些语言中,您可以为函数的参数设置默认值:
function Foo(arg1 = 50, arg2 = 'default') {
    //...
}
How do you do it in JavaScript?
你如何在 JavaScript 中做到这一点?
回答by James Long
In JavaScript, anything that isn't set is given the value undefined. This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:
在 JavaScript 中,任何未设置的都被赋予值undefined。这意味着如果您想为函数设置默认值,您的第一行需要检查这些值是否未定义:
function Foo(arg1, arg2) {
    if (typeof(arg1) === "undefined") { arg1 = 50; }
    if (typeof(arg2) === "undefined") { arg2 = "default"; }
}
You can take a bit of a short cut if you know roughly what those values will be:
如果您大致知道这些值是什么,您可以走一些捷径:
function Foo(arg1, arg2) {
    arg1 = arg1 || 50;
    arg2 = arg2 || "default";
}
However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null, undefined, falseor 0it'll be changed to 50, so be careful if you chose to use it
但是,如果这些参数为假,它们将被替换。这意味着如果 arg1 是一个空字符串, null, undefined,false或者0它会被改成 50,所以如果你选择使用它要小心
回答by Peter Rust
I prefer the == nullcheck instead of typeof(arg1) === undefined(as the jQuery library does internally: http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint). Not only is it more concise, it also handles both null and undefined, so that client code can pass in nulland get the default applied.
我更喜欢== null检查而不是typeof(arg1) === undefined(就像 jQuery 库在内部所做的那样:http: //docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint)。不仅更加简洁,而且还处理了null和undefined,这样客户端代码就可以传入null并应用默认值。
It is also possible to wrap the function in another function that supplies defaults. The prototypejs library has a function that supplies the argumentNames()(or if you don't want to use prototype, you can just borrow the implementation -- it's just a regex applied against the results of the function's toString()).
也可以将函数包装在另一个提供默认值的函数中。prototypejs 库有一个函数来提供argumentNames()(或者如果你不想使用原型,你可以借用实现——它只是一个针对函数的结果应用的正则表达式toString())。
So you could do something like this:
所以你可以做这样的事情:
var Foo = defaults(Foo, { arg1: 50, arg2: 'default' });
function Foo(arg1, arg2) {
  //...
}
And the implementation of defaults()would look something like this:
的实现defaults()看起来像这样:
function defaults(fn, def) {
  return function() {
    var arg_names = fn.argumentNames();
    var nArgs = args.length;
    for (var nArg = 0; nArg < nArgs; ++nArg) {
      if (arguments[nArg] == null && arg_names[nArg] in def)
        arguments[nArg] = def[arg_names[nArg]];
    }
    fn.apply(this, arguments);
  }
}
Of course, that's untested code and the way it's written, it requires the Prototype library. But all that said, the == nullapproach inside the function is more natural to Javascript, is easier to debug (you don't have another function layer to step through), and I find it easier to read:
当然,这是未经测试的代码,它的编写方式需要 Prototype 库。尽管如此,== null函数内部的方法对 Javascript 来说更自然,更容易调试(你没有另一个函数层可以单步执行),而且我发现它更容易阅读:
function Foo(arg1, arg2) {
  if (arg1 == null) arg1 = 50;
  if (arg2 == null) arg2 = 'default';
}
回答by JoeTidee
As of ES2015 (ES6), default parameters can be set like so:
从 ES2015 (ES6) 开始,可以像这样设置默认参数:
function multiply (a, b = 2) {
  return a * b;
}
multiply(5); // 10
回答by user113716
You would have to do it in the function body:
您必须在函数体中执行此操作:
function Foo(arg1 ,arg2) {
    if( typeof arg1 === 'undefined' )
        arg1 = 50;
    if( typeof arg2 === 'undefined' )
        arg2 = 'default';
    //...
}
Another way to test them for undefinedor nullis like this:
另一种方式来测试它们undefined或者null是这样的:
function Foo(arg1 ,arg2) {
    if( arg1 == undefined )
        arg1 = 50;
    if( arg2 == undefined )
        arg2 = 'default';
    //...
}
Some people don't like it because it is possible to override the value of undefinedsince it is just a global property. As long as it isn't overridden, this would work fine. If the parameters are nullor undefined, they'll be set to a default.
有些人不喜欢它,因为它undefined只是一个全局属性,因此可以覆盖 的值。只要它不被覆盖,这将正常工作。如果参数是null或undefined,它们将被设置为默认值。

