默认参数

如果没有传递任何值或 undefined,默认函数参数允许使用默认值初始化命名参数。

¥Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Try it

语法

¥Syntax

js
function fnName(param1 = defaultValue1, /* …, */ paramN = defaultValueN) {
  // …
}

描述

¥Description

在 JavaScript 中,函数参数默认为 undefined。但是,设置不同的默认值通常很有用。这是默认参数可以提供帮助的地方。

¥In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help.

在下面的示例中,如果在调用 multiply 时没有为 b 提供任何值,则在计算 a * bb 的值为 undefined,而 multiply 将返回 NaN

¥In the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return NaN.

js
function multiply(a, b) {
  return a * b;
}

multiply(5, 2); // 10
multiply(5); // NaN !

过去,设置默认值的一般策略是测试函数体中的参数值,如果是 undefined 就赋值。在以下示例中,如果仅使用一个参数调用 multiply,则 b 将设置为 1

¥In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. In the following example, b is set to 1 if multiply is called with only one argument:

js
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a * b;
}

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

使用默认参数,不再需要在函数体中进行检查。现在,你可以在函数头中将 1 指定为 b 的默认值:

¥With default parameters, checks in the function body are no longer necessary. Now, you can assign 1 as the default value for b in the function head:

js
function multiply(a, b = 1) {
  return a * b;
}

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

参数仍然从左到右设置,即使后面有没有默认值的参数,也会覆盖默认参数。

¥Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

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

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

注意:第一个默认参数及其后的所有参数不会对函数的 length 产生影响。

¥Note: The first default parameter and all parameters after it will not contribute to the function's length.

默认参数初始值设定项位于其自己的作用域中,该作用域是为函数体创建的作用域的父级。

¥The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.

这意味着可以在后面的参数的初始化程序中引用前面的参数。但是,在函数体中声明的函数和变量不能从默认值参数初始值设定项引用;尝试这样做会抛出运行时 ReferenceError。这还包括函数体中 var 声明的变量。

¥This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time ReferenceError. This also includes var-declared variables in the function body.

例如,以下函数在调用时将抛出 ReferenceError,因为默认参数值无权访问函数体的子作用域:

¥For example, the following function will throw a ReferenceError when invoked, because the default parameter value does not have access to the child scope of the function body:

js
function f(a = go()) {
  function go() {
    return ":P";
  }
}

f(); // ReferenceError: go is not defined

该函数将打印参数 a 的值,因为变量 var a 仅提升到为函数体创建的作用域的顶部,而不是为参数列表创建的父作用域,因此它的值对 b 不可见。

¥This function will print the value of the parameter a, because the variable var a is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to b.

js
function f(a, b = () => console.log(a)) {
  var a = 1;
  b();
}

f(); // undefined
f(5); // 5

示例

¥Examples

传递未定义的值与其他错误值

¥Passing undefined vs. other falsy values

在此示例的第二次调用中,即使第一个参数显式设置为 undefined(尽管不是 null 或其他 falsy 值),num 参数的值仍然是默认值。

¥In the second call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default.

js
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

默认参数在调用时计算。与 Python 不同(例如),每次调用函数时都会创建一个新对象。

¥The default argument is evaluated at call time. Unlike with Python (for example), a new object is created each time the function is called.

js
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:

js
function callSomething(thing = something()) {
  return thing;
}

let numberOfTimesCalled = 0;
function something() {
  numberOfTimesCalled += 1;
  return numberOfTimesCalled;
}

callSomething(); // 1
callSomething(); // 2

较早的参数可用于较晚的默认参数

¥Earlier parameters are available to later default parameters

前面(左侧)定义的参数可用于后面的默认参数:

¥Parameters defined earlier (to the left) are available to later default parameters:

js
function greet(name, greeting, message = `${greeting} ${name}`) {
  return [name, greeting, message];
}

greet("David", "Hi"); // ["David", "Hi", "Hi David"]
greet("David", "Hi", "Happy Birthday!"); // ["David", "Hi", "Happy Birthday!"]

此功能可以近似如下,它演示了处理了多少边缘情况:

¥This functionality can be approximated like this, which demonstrates how many edge cases are handled:

js
function go() {
  return ":P";
}

function withDefaults(
  a,
  b = 5,
  c = b,
  d = go(),
  e = this,
  f = arguments,
  g = this.value,
) {
  return [a, b, c, d, e, f, g];
}

function withoutDefaults(a, b, c, d, e, f, g) {
  switch (arguments.length) {
    case 0:
    case 1:
      b = 5;
    case 2:
      c = b;
    case 3:
      d = go();
    case 4:
      e = this;
    case 5:
      f = arguments;
    case 6:
      g = this.value;
  }
  return [a, b, c, d, e, f, g];
}

withDefaults.call({ value: "=^_^=" });
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]

withoutDefaults.call({ value: "=^_^=" });
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]

具有默认值分配的解构参数

¥Destructured parameter with default value assignment

你可以通过 解构赋值 语法使用默认值分配。

¥You can use default value assignment with the destructuring assignment syntax.

一种常见的方法是将空对象/数组设置为解构参数的默认值;例如:[x = 1, y = 2] = []。这使得可以不向函数传递任何内容,并且仍然预先填充这些值:

¥A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: [x = 1, y = 2] = []. This makes it possible to pass nothing to the function and still have those values prefilled:

js
function preFilledArray([x = 1, y = 2] = []) {
  return x + y;
}

preFilledArray(); // 3
preFilledArray([]); // 3
preFilledArray([2]); // 4
preFilledArray([2, 3]); // 5

// Works the same for objects:
function preFilledObject({ z = 3 } = {}) {
  return z;
}

preFilledObject(); // 3
preFilledObject({}); // 3
preFilledObject({ z: 2 }); // 2

规范

Specification
ECMAScript Language Specification
# sec-function-definitions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看