使用 ES6 / ES2015 设置 JavaScript 中的默认参数

您现在可以在 JavaScript 中定义函数参数的默认值. 默认值将在一个参数缺失或评估为未定义时使用。

用一个简单的例子很容易理解,注意当 y 未提供或未定义提供时如何使用值 3:

1function add(x, y = 3) {
2  console.log(x + y);
3}
4
5add(3, 9); // 12
6add(3) // 6
7add(12, undefined) // 15
8add(undefined, 8); // NaN, x doesn't have a default value

默认参数可以非常有用,以确保在执行操作时至少有一个空数组或对象字母可用。

1function addToGuestList(guests, list = []) {
2  console.log([...guests, ...list]);
3}
4
5addToGuestList(['Bob', 'Andy']); // ['Bob', 'Andy']
6addToGuestList(['Bob', 'Andy'], ['Roger']); // ['Bob', 'Andy', Roger]

同樣的例子沒有:

1function addToGuestList(guests, list) {
2  console.log([...guests, ...list]);
3}
4
5addToGuestList(['Bob', 'Andy']); // ['Bob', 'Andy', undefined]
6addToGuestList(['Bob', 'Andy'], ['Roger']); // ['Bob', 'Andy', Roger]
Published At
Categories with 技术
Tagged with
comments powered by Disqus