是的,这被称为默认参数
默认函数参数允许在没有传递值或未定义的情况下使用默认值初始化形式参数。
语法:
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
说明:
函数的参数默认为 undefined 但是,在某些情况下,设置不同的默认值可能很有用。这是默认参数可以提供帮助的地方。
过去,设置默认值的一般策略是在函数体中测试参数值,如果它们未定义,则为其赋值。如果调用中未提供任何值,则其值将是未定义的。您必须设置条件检查以确保参数不是未定义的
使用 ES2015 中的默认参数,不再需要在函数体中进行检查。现在您可以简单地在函数头中放置一个默认值。
差异示例:
// 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
不同的语法示例:
填充未定义与其他虚假值:
即使调用时显式设置了值,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)
在通话时评估:
默认参数在调用时进行评估,因此与其他一些语言不同,每次调用函数时都会创建一个新对象。
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
默认参数可供以后的默认参数使用:
已经遇到的参数可用于以后的默认参数
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.')
函数体内定义的函数:
在 Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30) 中引入。在函数体中声明的函数不能在默认参数中被引用并抛出一个 ReferenceError(当前是 SpiderMonkey 中的一个 TypeError,参见 bug 1022967)。默认参数总是最先执行,函数体内的函数声明在之后计算。
// Doesn't work! Throws ReferenceError.
function f(a = go()) {
function go() { return ':P'; }
}
默认参数后没有默认值的参数:
在 Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) 之前,以下代码会导致 SyntaxError。这已在错误 777060 中修复,并在以后的版本中按预期工作。参数仍然从左到右设置,即使后面有没有默认的参数,也会覆盖默认参数。
function f(x = 1, y) {
return [x, y];
}
f(); // [1, undefined]
f(2); // [2, undefined]
具有默认值分配的解构参数:
您可以使用带有解构赋值符号的默认值赋值
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
return x + y + z;
}
f(); // 6