函数的扩展
函数参数的默认值
ES6之前不能为函数参数指定默认值,只能通过变通的方式实现,代码如下。
function log(x, y) {
y = y || 'World';
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello World
上面的代码有个弊端,我们看最后一次log的调用,我们明明传递的是空字符串,有参数传递,但是空字符串在做布尔值运算时值为false
,c参数y
被赋予了’World’,我们想要的只是像第一次调用log函数那样,不传递第二个参数的情况下,才使用默认值’World’。
上面的弊端,可以用如下代码解决。
function log(x, y) {
//使用严格相等undefined判断参y是否传入
if(y===undefined){
y='World'
}
console.log(x, y);
}
console.log(log('Hello')) // Hello World
console.log(log('Hello', 'China')) // Hello China
console.log(log('Hello', '')) // Hello
ES6语法原生支持为函数参数指定默认值,用法更简洁,易读。用法如下代码。
function log(x, y='World') {
console.log(x, y);
}
console.log(log('Hello')) // Hello World
console.log(log('Hello', 'China')) // Hello China
console.log(log('Hello', '')) // Hello
注意事项
- 函数有同名参数时,不能给函数参数指定默认值,否则会报错
//正确
function foo(x, x, y) {
console.log("x:",x,"y:",y);
}
console.log(foo(1,2,3)); //x: 2 y: 3
//Uncaught SyntaxError: Duplicate parameter name not allowed in this context
//未捕获的SyntaxError:在此上下文中不允许重复的参数名称
function foo(x,x, y=1) {
console.log("x:",x,"y:",y);
}
console.log(foo(1,2));
- 参数的默认值是惰性求值的
也就是说,参数的默认值是每次调用函数都会做一次求值运算,而不是总是使用声明参数时的默认值
let x=100
function foo(x,y=x+1){
return [x,y];
}
console.log(foo(x));// [100,101]
x=200;
console.log(foo(x));// [200,201]
一开始x=100
,调用foo
函数返回[100,101]
,x=200
,调用foo
函数返回[200,201]
,这说明每次调用参数y
的默认值都会重新计算。
与解构赋值默认值结合使用
下面是一个函数参数的解构赋值
function foo({
x=1,y=2}){
return [x,y];
}
console.log(foo({
x:11,y:22}));// [11,22]
console.log(foo({
x:11}));// [11,2]
console.log(foo({
y:22}));// [1,22]
console.log(<