简体   繁体   English

为 JavaScript 函数设置默认参数值

[英]Set a default parameter value for a JavaScript function

I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed).我希望 JavaScript 函数具有我设置默认值的可选参数,如果未定义该值(如果传递该值则忽略该值)。 In Ruby you can do it like this:在 Ruby 中,你可以这样做:

def read_file(file, delete_after = false)
  # code
end

Does this work in JavaScript?这在 JavaScript 中有效吗?

function read_file(file, delete_after = false) {
  // Code
}

From ES6/ES2015 , default parameters are in the language specification.ES6/ES2015 开始,默认参数在语言规范中。

function read_file(file, delete_after = false) {
  // Code
}

just works.只是工作。

Reference: Default Parameters - MDN参考: 默认参数 - MDN

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.如果未传递任何值未定义,则默认函数参数允许使用默认值初始化形式参数。

In ES6, you can simulate default named parameters via destructuring :在 ES6 中,您可以通过解构模拟默认命名参数

// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
    // Use the variables `start`, `end` and `step` here
    ···
}

// sample call using an object
myFor({ start: 3, end: 0 });

// also OK
myFor();
myFor({});

Pre ES2015 , ES2015 之前

There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null.有很多方法,但这是我的首选方法——它可以让你传入任何你想要的东西,包括 false 或 null。 ( typeof null == "object" ) ( typeof null == "object" )

function foo(a, b) {
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}
function read_file(file, delete_after) {
    delete_after = delete_after || "my default here";
    //rest of code
}

This assigns to delete_after the value of delete_after if it is not a falsey value otherwise it assigns the string "my default here" .这会将delete_after的值分配给delete_after如果它不是false值,否则它分配字符串"my default here" For more detail, check out Doug Crockford's survey of the language and check out the section on Operators .有关更多详细信息,请查看Doug Crockford 对语言的调查并查看有关 Operators 的部分

This approach does not work if you want to pass in a falsey value ie false , null , undefined , 0 or "" .如果您想传入一个虚假的值,即falsenullundefined0"" ,则此方法不起作用。 If you require falsey values to be passed in you would need to use the method in Tom Ritter's answer .如果您需要传入 falsey值,则需要使用Tom Ritter's answer中的方法。

When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then merge these values with an object that contains the default values for the function在处理函数的多个参数时,允许使用者在对象中传递参数参数然后这些值与包含函数默认值的对象合并通常很有用

function read_file(values) {
    values = merge({ 
        delete_after : "my default here"
    }, values || {});

    // rest of code
}

// simple implementation based on $.extend() from jQuery
function merge() {
    var obj, name, copy,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length;

    for (; i < length; i++) {
        if ((obj = arguments[i]) != null) {
            for (name in obj) {
                copy = obj[name];

                if (target === copy) {
                    continue;
                }
                else if (copy !== undefined) {
                    target[name] = copy;
                }
            }
        }
    }

    return target;
};

to use使用

// will use the default delete_after value
read_file({ file: "my file" }); 

// will override default delete_after value
read_file({ file: "my file", delete_after: "my value" }); 

I find something simple like this to be much more concise and readable personally.我发现像这样简单的东西更简洁易读。

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
} 

In ECMAScript 6 you will actually be able to write exactly what you have:在 ECMAScript 6 中,您实际上将能够准确地编写您所拥有的内容:

function read_file(file, delete_after = false) {
  // Code
}

This will set delete_after to false if it s not present or undefined .如果它不存在或undefined ,这会将delete_after设置为false You can use ES6 features like this one today with transpilers such as Babel .您现在可以将像这样的 ES6 功能与Babel等转译器一起使用。

See the MDN article for more information . 有关详细信息,请参阅 MDN 文章

Default Parameter Values默认参数值

With ES6, you can do perhaps one of the most common idioms in JavaScript relates to setting a default value for a function parameter.使用 ES6,您可以执行JavaScript中最常见的习惯用法之一,即为函数参数设置默认值。 The way we've done this for years should look quite familiar:我们多年来这样做的方式应该看起来很熟悉:

function foo(x,y) {
 x = x || 11;
 y = y || 31;
 console.log( x + y );
}
foo(); // 42
foo( 5, 6 ); // 11
foo( 5 ); // 36
foo( null, 6 ); // 17

This pattern is most used, but is dangerous when we pass values like这种模式是最常用的,但是当我们传递像这样的值时很危险

foo(0, 42)
foo( 0, 42 ); // 53 <-- Oops, not 42

Why?为什么? Because the 0 is falsy , and so the x || 11 results in 11因为0 is falsy ,所以x || 11 results in 11 x || 11 results in 11 , not the directly passed in 0. To fix this gotcha, some people will instead write the check more verbosely like this: x || 11 results in 11 ,而不是直接传入的 0 。为了解决这个问题,有些人会改为更详细地编写检查,如下所示:

function foo(x,y) {
 x = (x !== undefined) ? x : 11;
 y = (y !== undefined) ? y : 31;
 console.log( x + y );
}
foo( 0, 42 ); // 42
foo( undefined, 6 ); // 17

we can now examine a nice helpful syntax added as of ES6 to streamline the assignment of default values to missing arguments:我们现在可以检查从ES6开始添加的一个很好的有用语法,以简化将默认值分配给缺失参数的过程:

function foo(x = 11, y = 31) {
 console.log( x + y );
}

foo(); // 42
foo( 5, 6 ); // 11
foo( 0, 42 ); // 42
foo( 5 ); // 36
foo( 5, undefined ); // 36 <-- `undefined` is missing
foo( 5, null ); // 5 <-- null coerces to `0`
foo( undefined, 6 ); // 17 <-- `undefined` is missing
foo( null, 6 ); // 6 <-- null coerces to `0`

x = 11 in a function declaration is more like x !== undefined ? x : 11函数声明中的x = 11更像x !== undefined ? x : 11 x !== undefined ? x : 11 than the much more common idiom x || 11 x !== undefined ? x : 11比更常见的习语x || 11 x || 11

Default Value Expressions默认值表达式

Function default values can be more than just simple values like 31; Function默认值可以不仅仅是像 31 这样的简单值; they can be any valid expression, even a function call :它们可以是任何有效的表达式,甚至是function call

function bar(val) {
 console.log( "bar called!" );
 return y + val;
}
function foo(x = y + 3, z = bar( x )) {
 console.log( x, z );
}
var y = 5;
foo(); // "bar called"
 // 8 13
foo( 10 ); // "bar called"
 // 10 15
y = 6;
foo( undefined, 10 ); // 9 10

As you can see, the default value expressions are lazily evaluated, meaning they're only run if and when they're needed — that is, when a parameter's argument is omitted or is undefined.如您所见,默认值表达式是惰性求值的,这意味着它们仅在需要时运行——即,当参数的参数被省略或未定义时。

A default value expression can even be an inline function expression call — commonly referred to as an Immediately Invoked Function Expression (IIFE) :默认值表达式甚至可以是内联函数表达式调用——通常称为立即调用函数表达式(IIFE)

function foo( x =
 (function(v){ return v + 11; })( 31 )
) {
 console.log( x );
}
foo(); // 42

that solution is work for me in js:该解决方案在 js 中对我有用:

function read_file(file, delete_after) {
    delete_after = delete_after || false;
    // Code
}

I would highly recommend extreme caution when using default parameter values in javascript.我强烈建议在 javascript 中使用默认参数值时要格外小心。 It often creates bugs when used in conjunction with higher order functions like forEach , map , and reduce .当与forEachmapreduce等高阶函数结合使用时,它通常会产生错误。 For example, consider this line of code:例如,考虑这行代码:

['1', '2', '3'].map(parseInt); // [1, NaN, NaN]

parseInt has an optional second parameter function parseInt(s, [ radix =10]) but map calls parseInt with three arguments: ( element , index , and array ). parseInt 有一个可选的第二个参数function parseInt(s, [ radix =10])但 map 使用三个参数调用parseInt :(元素索引数组)。

I suggest you separate your required parameters form your optional/default valued arguments.我建议您将所需参数与可选/默认值参数分开。 If your function takes 1,2, or 3 required parameters for which no default value makes sense, make them positional parameters to the function, any optional parameters should follow as named attributes of a single object.如果您的函数需要 1、2 或 3 个必需参数,而默认值对这些参数没有意义,请将它们设为函数的位置参数,任何可选参数都应作为单个对象的命名属性跟随。 If your function takes 4 or more, perhaps it makes more sense to supply all arguments via attributes of a single object parameter.如果您的函数需要 4 个或更多,那么通过单个对象参数的属性提供所有参数可能更有意义。

In your case I would suggest you write your deleteFile function like this: ( edited per instead 's comments )...在您的情况下,我建议您像这样编写您的 deleteFile 函数:(根据instead评论进行编辑)...

 // unsafe function read_file(fileName, deleteAfter=false) { if (deleteAfter) { console.log(`Reading and then deleting ${fileName}`); } else { console.log(`Just reading ${fileName}`); } } // better function readFile(fileName, options) { const deleteAfter = !!(options && options.deleteAfter === true); read_file(fileName, deleteAfter); } console.log('unsafe...'); ['log1.txt', 'log2.txt', 'log3.txt'].map(read_file); console.log('better...'); ['log1.txt', 'log2.txt', 'log3.txt'].map(readFile);

Running the above snippet illustrates the dangers lurking behind default argument values for unused parameters.运行上面的代码片段说明了潜伏在未使用参数的默认参数值背后的危险。

Just use an explicit comparison with undefined.只需使用未定义的显式比较。

function read_file(file, delete_after)
{
    if(delete_after === undefined) { delete_after = false; }
}

As an update...with ECMAScript 6 you can FINALLY set default values in function parameter declarations like so:作为更新...使用 ECMAScript 6,您最终可以在函数参数声明中设置默认值,如下所示:

function f (x, y = 7, z = 42) {
  return x + y + z
}

f(1) === 50

As referenced by - http://es6-features.org/#DefaultParameterValues正如所引用的 - http://es6-features.org/#DefaultParameterValues

being a long time C++ developer (Rookie to web development :)), when I first came across this situation, I did the parameter assignment in the function definition, like it is mentioned in the question, as follows.作为一个长期的C ++开发人员(Rookie to web development :)),当我第一次遇到这种情况时,我在函数定义中进行了参数分配,就像问题中提到的那样,如下所示。

function myfunc(a,b=10)

But beware that it doesn't work consistently across browsers.但请注意,它不能在浏览器中一致地工作。 For me it worked on chrome on my desktop, but did not work on chrome on android.对我来说,它适用于我桌面上的 chrome,但不适用于 android 上的 chrome。 Safer option, as many have mentioned above is -正如上面许多人提到的那样,更安全的选择是 -

    function myfunc(a,b)
    {
    if (typeof(b)==='undefined') b = 10;
......
    }

Intention for this answer is not to repeat the same solutions, what others have already mentioned, but to inform that parameter assignment in the function definition may work on some browsers, but don't rely on it.此答案的目的不是重复其他人已经提到的相同解决方案,而是告知函数定义中的参数分配可能适用于某些浏览器,但不要依赖它。

To anyone interested in having there code work in Microsoft Edge, do not use defaults in function parameters.对于有兴趣让代码在 Microsoft Edge 中工作的任何人,请不要在函数参数中使用默认值。

function read_file(file, delete_after = false) {
    #code
}

In that example Edge will throw an error "Expecting ')'"在该示例中,Edge 将抛出错误“期望')'”

To get around this use为了解决这个问题

function read_file(file, delete_after) {
  if(delete_after == undefined)
  {
    delete_after = false;
  }
  #code
}

As of Aug 08 2016 this is still an issue截至 2016 年 8 月 8 日,这仍然是一个问题

If you are using ES6+ you can set default parameters in the following manner:如果您使用的是ES6+ ,您可以通过以下方式设置默认参数:

 function test (foo = 1, bar = 2) { console.log(foo, bar); } test(5); // foo gets overwritten, bar remains default parameter

If you need ES5 syntax you can do it in the following manner:如果您需要ES5语法,可以通过以下方式进行:

 function test(foo, bar) { foo = foo || 2; bar = bar || 0; console.log(foo, bar); } test(5); // foo gets overwritten, bar remains default parameter

In the above syntax the OR operator is used.在上述语法中,使用了OR运算符。 The OR operator always returns the first value if this can be converted to true if not it returns the righthandside value.如果可以将其转换为true ,则OR运算符始终返回第一个值,否则返回右侧的值。 When the function is called with no corresponding argument the parameter variable ( bar in our example) is set to undefined by the JS engine.当函数在没有相应参数的情况下被调用时,JS 引擎将参数变量(在我们的示例中为bar )设置为undefined undefined Is then converted to false and thus does the OR operator return the value 0. undefined然后转换为 false,因此OR运算符返回值 0。

As per the syntax根据语法

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

you can define the default value of formal parameters.您可以定义形式参数的默认值。 and also check undefined value by using typeof function.并使用typeof函数检查未定义的值。

function helloWorld(name, symbol = '!!!') {
    name = name || 'worlds';
    console.log('hello ' + name + symbol);
}

helloWorld(); // hello worlds!!!

helloWorld('john'); // hello john!!!

helloWorld('john', '(>.<)'); // hello john(>.<)

helloWorld('john', undefined); // hello john!!!

helloWorld(undefined, undefined); // hello worlds!!!

Use this if you want to use latest ECMA6 syntax:如果您想使用最新ECMA6语法,请使用此选项:

 function myFunction(someValue = "This is DEFAULT!") { console.log("someValue --> ", someValue); } myFunction("Not A default value") // calling the function without default value myFunction() // calling the function with default value

It is called default function parameters .它被称为default function parameters It allows formal parameters to be initialized with default values if no value or undefined is passed.如果没有传递任何值或未定义,它允许使用默认值初始化形式参数。 NOTE : It wont work with Internet Explorer or older browsers.注意:它不适用于 Internet Explorer 或更旧的浏览器。

For maximum possible compatibility use this:为了最大可能的兼容性,请使用:

 function myFunction(someValue) { someValue = (someValue === undefined) ? "This is DEFAULT!" : someValue; console.log("someValue --> ", someValue); } myFunction("Not A default value") // calling the function without default value myFunction() // calling the function with default value

Both functions have exact same behavior as each of these example rely on the fact that the parameter variable will be undefined if no parameter value was passed when calling that function.这两个函数具有完全相同的行为,因为这些示例中的每一个都依赖于这样一个事实,即如果在调用该函数时没有传递参数值,则参数变量将是undefined的。

ES6: As already mentioned in most answers, in ES6, you can simply initialise a parameter along with a value. ES6:正如大多数答案中已经提到的,在 ES6 中,您可以简单地初始化一个参数和一个值。


ES5: Most of the given answers aren't good enough for me because there are occasions where I may have to pass falsey values such as 0 , null and undefined to a function. ES5:大多数给定的答案对我来说都不够好,因为在某些情况下我可能不得不将虚假值(例如0nullundefined )传递给函数。 To determine if a parameter is undefined because that's the value I passed instead of undefined due to not have been defined at all I do this:要确定参数是否未定义,因为那是我传递的值而不是由于根本没有定义而未定义的值,我这样做:

function foo (param1, param2) {
   param1 = arguments.length >= 1 ? param1 : "default1";
   param2 = arguments.length >= 2 ? param2 : "default2";
}

 function throwIfNoValue() { throw new Error('Missing argument'); } function foo(argValue = throwIfNoValue()) { return argValue ; }

Here foo() is a function which has a parameter named argValue.这里 foo() 是一个函数,它有一个名为 argValue 的参数。 If we don't pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue.如果我们在此处的函数调用中不传递任何内容,则将调用函数 throwIfNoValue(),并将返回的结果分配给唯一的参数 argValue。 This is how a function call can be used as a default parameter.这就是函数调用可以用作默认参数的方式。 Which makes the code more simplified and readable.这使代码更加简化和可读。

This example has been taken from here这个例子取自这里

If for some reason you are not on ES6 and are using lodash here is a concise way to default function parameters via _.defaultTo method:如果由于某种原因您不在ES6 上并且正在使用lodash ,那么这是通过_.defaultTo方法默认函数参数的简洁方法:

 var fn = function(a, b) { a = _.defaultTo(a, 'Hi') b = _.defaultTo(b, 'Mom!') console.log(a, b) } fn() // Hi Mom! fn(undefined, null) // Hi Mom! fn(NaN, NaN) // Hi Mom! fn(1) // 1 "Mom!" fn(null, 2) // Hi 2 fn(false, false) // false false fn(0, 2) // 0 2
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Which will set the default if the current value is NaN , null , or undefined如果当前值为NaNnullundefined ,它将设置默认值

Yes, using default parameters is fully supported in ES6 :是的, ES6完全支持使用默认参数:

function read_file(file, delete_after = false) {
  // Code
}

or或者

const read_file = (file, delete_after = false) => {
    // Code
}

but prior in ES5 you could easily do this:但是在ES5之前你可以很容易地做到这一点:

function read_file(file, delete_after) {
  var df = delete_after || false;
  // Code
}

Which means if the value is there, use the value, otherwise, use the second value after ||这意味着如果该值存在,则使用该值,否则,使用||之后的第二个值operation which does the same thing...做同样事情的操作......

Note: also there is a big difference between those if you pass a value to ES6 one even the value be falsy, that will be replaced with new value, something like null or "" ... but ES5 one only will be replaced if only the passed value is truthy, that's because the way ||注意:如果您将一个值传递给ES6一个,即使该值是虚假的,这也有很大的不同,它将被替换为新值,例如null"" ...但只有ES5一个才会被替换传递的值是真实的,那是因为方式|| working...在职的...

Sounds of Future未来之声

In future, you will be able to "spread" one object to another (currently as of 2019 NOT supported by Edge !) - demonstration how to use that for nice default options regardless of order:将来,您将能够将一个对象“传播”到另一个对象(从 2019 年开始,Edge 不支持!) - 演示如何将其用于不错的默认选项,而不管顺序如何:

 function test(options) { var options = { // defaults url: 'defaultURL', some: 'somethingDefault', // override with input options ...options }; var body = document.getElementsByTagName('body')[0]; body.innerHTML += '<br>' + options.url + ' : ' + options.some; } test(); test({}); test({url:'myURL'}); test({some:'somethingOfMine'}); test({url:'overrideURL', some:'andSomething'}); test({url:'overrideURL', some:'andSomething', extra:'noProblem'});

MDN reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax MDN 参考: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

...meanwhile what Edge DOES support is Object.assign() (IE does not, but I really hope we can leave IE behind :) ) ...与此同时, Edge 支持的是 Object.assign() (IE 不支持,但我真的希望我们可以将 IE 抛在后面 :))

Similarly you could do同样你可以做

 function test(options) { var options = Object.assign({ // defaults url: 'defaultURL', some: 'somethingDefault', }, options); // override with input options var body = document.getElementsByTagName('body')[0]; body.innerHTML += '<br>' + options.url + ' : ' + options.some; } test(); test({}); test({url:'myURL'}); test({some:'somethingOfMine'}); test({url:'overrideURL', some:'andSomething'}); test({url:'overrideURL', some:'andSomething', extra:'noProblem'});

EDIT: Due to comments regarding const options - the problem with using constant options in the rest of the function is actually not that you can't do that, is just that you can't use the constant variable in its own declaration - you would have to adjust the input naming to something like编辑:由于对const选项的评论 - 在函数的其余部分使用常量选项的问题实际上不是你不能这样做,只是你不能在自己的声明中使用常量变量 - 你会必须将输入命名调整为类似

function test(input_options){
   const options = {
     // defaults
     someKey:    'someDefaultValue',
     anotherKey: 'anotherDefaultValue',

     // merge-in input options
     ...input_options
   };

   // from now on use options with no problem
}

Just to showcase my skills too (lol), above function can written even without having named arguments as below:只是为了展示我的技能(大声笑),即使没有命名参数也可以编写上述函数,如下所示:

ES5 and above ES5 及以上

function foo() {
    a = typeof arguments[0] !== 'undefined' ? a : 42;
    b = typeof arguments[1] !== 'undefined' ? b : 'default_b';
    ...
}

ES6 and above ES6 及以上

function foo(...rest) {
    a = typeof rest[0] !== 'undefined' ? a : 42;
    b = typeof rest[1] !== 'undefined' ? b : 'default_b';
    ...
}

Yes - proof:是的 - 证明:

 function read_file(file, delete_after = false) { // Code console.log({file,delete_after}); } // TEST read_file("A"); read_file("B",true); read_file("C",false);

Yeah this is referred to as a default parameter是的,这被称为默认参数

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.如果未传递任何值或未定义,则默认函数参数允许使用默认值初始化形式参数。

Syntax:句法:

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

Description:描述:

Parameters of functions default to undefined However, in situations it might be useful to set a different default value.函数的参数默认为 undefined 但是,在某些情况下,设置不同的默认值可能很有用。 This is where default parameters can help.这是默认参数可以提供帮助的地方。

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined.过去,设置默认值的一般策略是在函数体中测试参数值,如果它们未定义,则为其赋值。 If no value is provided in the call, its value would be undefined.如果调用中未提供任何值,则其值将是未定义的。 You would have to set a conditional check to make sure the parameter is not undefined您必须设置条件检查以确保参数未定义

With default parameters in ES2015, the check in the function body is no longer necessary.使用 ES2015 中的默认参数,不再需要在函数体中进行检查。 Now you can simply put a default value in the function head.现在您可以简单地在函数头中放置一个默认值。

Example of the differences:差异示例:

// OLD METHOD
function multiply(a, b) {
  b = (typeof b !== 'undefined') ?  b : 1;
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5


// NEW METHOD
function multiply(a, b = 1) {
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5

Different Syntax Examples:不同的语法示例:

Padding undefined vs other falsy values:填充未定义与其他虚假值:

Even if the value is set explicitly when calling, the value of the num argument is the default one.即使在调用时显式设置了值,num 参数的值也是默认值。

function test(num = 1) {
  console.log(typeof num);
}

test();          // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)

// test with other falsy values:
test('');        // 'string' (num is set to '')
test(null);      // 'object' (num is set to null)

Evaluated at call time:在通话时评估:

The default argument gets evaluated at call time, so unlike some other languages, a new object is created each time the function is called.默认参数在调用时进行评估,因此与其他一些语言不同,每次调用函数时都会创建一个新对象。

function append(value, array = []) {
  array.push(value);
  return array;
}

append(1); //[1]
append(2); //[2], not [1, 2]


// This even applies to functions and variables
function callSomething(thing = something()) {
 return thing;
}

function something() {
  return 'sth';
}

callSomething();  //sth

Default parameters are available to later default parameters:默认参数可用于以后的默认参数:

Params already encountered are available to later default parameters已经遇到的参数可用于以后的默认参数

function singularAutoPlural(singular, plural = singular + 's',
                        rallyingCry = plural + ' ATTACK!!!') {
  return [singular, plural, rallyingCry];
}

//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural('Gecko');

//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural('Fox', 'Foxes');

//["Deer", "Deer", "Deer ... change."]
singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \ petition the government for positive change.')

Functions defined inside function body:函数体内定义的函数:

Introduced in Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30).在 Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30) 中引入。 Functions declared in the function body cannot be referred inside default parameters and throw a ReferenceError (currently a TypeError in SpiderMonkey, see bug 1022967).在函数体中声明的函数不能在默认参数中被引用并抛出一个 ReferenceError(当前是 SpiderMonkey 中的一个 TypeError,参见 bug 1022967)。 Default parameters are always executed first, function declarations inside the function body evaluate afterwards.默认参数总是首先执行,然后函数体内的函数声明求值。

// Doesn't work! Throws ReferenceError.
function f(a = go()) {
  function go() { return ':P'; }
}

Parameters without defaults after default parameters:默认参数后无默认参数:

Prior to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), the following code resulted in a SyntaxError.在 Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) 之前,以下代码会导致 SyntaxError。 This has been fixed in bug 777060 and works as expected in later versions.这已在错误 777060 中修复,并在以后的版本中按预期工作。 Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.参数仍然从左到右设置,覆盖默认参数,即使后面有没有默认的参数。

function f(x = 1, y) {
  return [x, y];
}

f(); // [1, undefined]
f(2); // [2, undefined]

Destructured paramet with default value assignment:具有默认值分配的解构参数:

You can use default value assignment with the destructuring assignment notation您可以将默认值赋值与解构赋值表示法一起使用

function f([x, y] = [1, 2], {z: z} = {z: 3}) {
  return x + y + z;
}

f(); // 6

I've noticed a few answers mentioning that using default params isn't portable to other browsers, but it's only fair to point out that you can use transpilers like Babel to convert your code into ES5 syntax for browsers that have limited support for modern JS features.我注意到一些答案提到使用默认参数不能移植到其他浏览器,但公平地指出,您可以使用 Babel 之类的编译器将代码转换为对现代 JS 支持有限的浏览器的 ES5 语法特征。

So this:所以这:

function read_file(file, delete_after = false) {
  // Code
}

would be transpiled as this (try it out in the Babel REPL -> https://babeljs.io/repl/ ):将被编译成这样(在 Babel REPL -> https://babeljs.io/repl/中尝试一下):

"use strict";

function read_file(file) {

  var delete_after =
    arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  
  //Code...

}

Of course, if you have no intention of using transpilation, then setting default params in the body of the function like others have demonstrated is perfectly fine as well.当然,如果您不打算使用转译,那么像其他人演示的那样在函数体中设置默认参数也很好。

def read_file(file, delete_after = false)
  # code
end

Following code may work in this situation including ECMAScript 6 (ES6) as well as earlier versions.以下代码可能适用于这种情况,包括 ECMAScript 6 (ES6) 以及早期版本。

 function read_file(file, delete_after) { if(delete_after == undefined) delete_after = false;//default value console.log('delete_after =',delete_after); } read_file('text1.txt',true); read_file('text2.txt');

as default value in languages works when the function's parameter value is skipped when calling, in JavaScript it is assigned to undefined .当调用时跳过函数的参数值时,语言中的默认值起作用,在 JavaScript 中,它被分配给undefined This approach doesn't look attractive programmatically but have backward compatibility .这种方法在编程上看起来并不吸引人,但具有向后兼容性

Just a different approach to set default params is to use object map of arguments, instead of arguments directly.设置默认参数的另一种方法是使用参数的对象映射,而不是直接使用参数。 For example,例如,

const defaultConfig = {
 category: 'Animals',
 legs: 4
};

function checkOrganism(props) {
 const category = props.category || defaultConfig.category;
 const legs = props.legs || defaultConfig.legs;
}

This way, it's easy to extend the arguments and not worry about argument length mismatch.这样,很容易扩展参数,而不必担心参数长度不匹配。

export const getfilesize = (bytes, decimals = 2) => {
    if (bytes === 0){ 
        return '0 Bytes';
    }else{
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];

    }
}

The answer is yes.答案是肯定的。 In fact, there are many languages who support default parameters.事实上,支持默认参数的语言有很多。 Python is one of them: Python就是其中之一:

def(a, enter="Hello"):
   print(a+enter)

Even though this is Python 3 code due to the parentheses, default parameters in functions also work in JS.尽管由于括号这是 Python 3 代码,但函数中的默认参数也适用于 JS。

For example, and in your case:例如,在您的情况下:

 function read_file(file, deleteAfter=false){ console.log(deleteAfter); } read_file("test.txt");

But sometimes you don't really need default parameters.但有时你并不真的需要默认参数。

You can just define the variable right after the start of the function, like this:您可以在函数开始后立即定义变量,如下所示:

 function read_file(file){ var deleteAfter = false; console.log(deleteAfter); } read_file("test.txt");

In both of my examples, it returns the same thing.在我的两个示例中,它返回相同的内容。 But sometimes they actually could be useful, like in very advanced projects.但有时它们实际上可能很有用,比如在非常高级的项目中。

So, in conclusion, default parameter values can be used in JS.所以,总而言之,在 JS 中可以使用默认参数值。 But it is almost the same thing as defining a variable right after the start of the function.但这与在函数开始后立即定义变量几乎相同。 However, sometimes they are still very useful.但是,有时它们仍然非常有用。 As you have may noticed, default parameter values take 1 less line of code than the standard way which is defining the parameter right after the start of the function.您可能已经注意到,默认参数值比在函数开始后立即定义参数的标准方法少了 1 行代码。

EDIT: And this is super important!编辑:这非常重要! This will not work in IE.这在 IE 中不起作用 See documentation .请参阅文档 So with IE you have to use the "define variable at top of function" method.因此,对于 IE,您必须使用“在函数顶部定义变量”方法。 Default parameters won't work in IE.默认参数在 IE 中不起作用。

Yes, This will work in Javascript.是的,这将在 Javascript 中工作。 You can also do that:你也可以这样做:

function func(a=10,b=20)
{
    alert (a+' and '+b);
}

func(); // Result: 10 and 20

func(12); // Result: 12 and 20

func(22,25); // Result: 22 and 25

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

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