MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

翻譯不完整。請協助 翻譯此英文文件

函式預設參數 允許沒有值傳入或是傳入值為 undefined 的情況下,參數能以指定的預設值初始化。

語法

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

說明

在 JavaScript 中,函式的參數預設值都為 undefined 。然而,指定不同的預設值可能在一些場景很有用。這也是函式參數預設值可以幫上忙的地方。

在過去,設定預設值的普遍方法為:在函式的內容裡檢查傳入參數是否為 undefined ,如果是的話,爲他指定一個值。如下列範例,若函式被呼叫時,並沒有提供 b 的值,它的值就會是 undefined,在計算 a*b 時,以及呼叫 multiply 時,就會回傳 NaN。然而這在範例的第二行被阻止了::

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

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

有了 ES2015 的預設參數,再也不用於函式進行檢查了,現在只要簡單的在函式的起始處為 b 指定 1 的值:

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

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

範例

傳入 undefined

這邊第二段函式呼叫中,僅管第二個傳入參數在呼叫時明確地指定為undefined(雖不是null),其顏色參數的值是預設值(rosybrown)。

function setBackgroundColor(element, color = 'rosybrown') {
  element.style.backgroundColor = color;
}

setBackgroundColor(someDiv);            // color set to 'rosybrown'
setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' too
setBackgroundColor(someDiv, 'blue');    // color set to 'blue' 

Evaluated at call time

The default argument gets evaluated at call time, so unlike e.g. in Python, 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

Parameters 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.')

This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled.

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:
      a;
    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;
    default:
  }
  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, "=^_^="]

Functions defined inside function body

Introduced in 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). 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. This has been fixed in bug 777060 and works as expected in later versions. 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 parameter 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

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Function Definitions' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Function Definitions' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 49 15.0 (15.0) Edge No support 10
Parameters without defaults after default parameters 49 26.0 (26.0) ? ? 10
Destructured parameter with default value assignment 49 41.0 (41.0) ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support 49 15.0 (15.0) No support No support No support 49
Parameters without defaults after default parameters No support 49 26.0 (26.0) ? ? ? 49
Destructured parameter with default value assignment No support ? 41.0 (41.0) ? ? ? ?

See also

文件標籤與貢獻者

 此頁面的貢獻者: jsgao0, Snailpool
 最近更新: jsgao0,