ES6 引入了函数参数的默认值(Default Parameters)功能,允许在函数定义时为某些参数提供默认值。当调用函数时,如果这些参数没有传递值(或传递的值为 undefined
),则会使用默认值。
1. 基本语法
默认值语法非常简单,只需要在参数名后使用等号 =
来指定默认值:
function greet(name = 'Guest') {console.log(`Hello, ${name}!`);
}greet(); // 输出: Hello, Guest!
greet('Alice'); // 输出: Hello, Alice!
在上面的例子中,name
参数的默认值是 'Guest'
。当调用 greet()
时,如果没有传递 name
参数,函数会使用默认值 'Guest'
。
2. 多个参数的默认值
你可以为多个函数参数设置默认值:
function createProfile(name = 'John Doe', age = 30) {console.log(`Name: ${name}, Age: ${age}`);
}createProfile(); // 输出: Name: John Doe, Age: 30
createProfile('Alice'); // 输出: Name: Alice, Age: 30
createProfile('Bob', 25); // 输出: Name: Bob, Age: 25
如果只传递了一个参数,另一个参数会使用它的默认值。
3. 默认值与其他参数的结合
默认参数可以与其他普通参数结合使用,只要确保默认参数的位置在没有默认值的参数之后。例如:
function sum(a, b = 5, c = 10) {return a + b + c;
}console.log(sum(2)); // 输出: 17, 因为 b 默认是 5, c 默认是 10
console.log(sum(2, 3)); // 输出: 15, 因为 c 默认是 10
console.log(sum(2, 3, 4)); // 输出: 9
4. 动态计算默认值
默认值也可以是一个表达式,甚至可以是一个函数调用。这个表达式会在函数调用时求值并赋值给参数:
function getMax(a, b = Math.max(a, 100)) {console.log(`Max value: ${b}`);
}getMax(50); // 输出: Max value: 100
getMax(200); // 输出: Max value: 200
在上面的例子中,如果 b
没有传递值,默认值 Math.max(a, 100)
会被计算出来。
5. 默认值与 undefined
的行为
需要注意的是,默认值只在参数为 undefined
时生效。如果传递了 null
或其他值,则不会使用默认值:
function greet(name = 'Guest') {console.log(`Hello, ${name}!`);
}greet(undefined); // 输出: Hello, Guest!
greet(null); // 输出: Hello, null!
6. 与解构赋值的结合
当函数参数是一个对象或数组时,可以与解构赋值结合使用,为解构的属性设置默认值:
// 对象解构
function printUserInfo({ name = 'Guest', age = 18 } = {}) {console.log(`Name: ${name}, Age: ${age}`);
}printUserInfo(); // 输出: Name: Guest, Age: 18
printUserInfo({ name: 'Alice' }); // 输出: Name: Alice, Age: 18
printUserInfo({ age: 25 }); // 输出: Name: Guest, Age: 25// 数组解构
function printCoordinates([x = 0, y = 0] = []) {console.log(`X: ${x}, Y: ${y}`);
}printCoordinates(); // 输出: X: 0, Y: 0
printCoordinates([10]); // 输出: X: 10, Y: 0
printCoordinates([10, 20]); // 输出: X: 10, Y: 20
总结
ES6 的函数参数默认值简化了代码,使得函数更加灵活和易用。它允许开发者为函数参数设置默认值,避免了在函数内部编写冗长的检查代码。同时,默认值的引入使得代码更加简洁、易懂,并且能够与其他特性(如解构赋值)结合使用,提升了编程效率。