生效条件对比:
函数默认值-不传参数
解构默认值-1)不传参数2)传undefined作为参数
function fun({ x = 1 } = { x: 2 }) {
console.log(x);
}
fun(); //2
fun({}); //1
解析步骤:
1.是否传参
传参,使用传入的参数(此案例参数是对象)
未传参,使用参数默认值
2.若未设置参数默认值,使用解构默认值
function fun({ x = 1 } = {}, { y } = { y: 2 }) {
console.log(x, y);
}
fun(); //1 2
fun({}, {}); //1 undefined
其中,{ x = 10 } 是解构默认值, { y: 10 }是参数默认值
1)fun();
给形参x,y,均未传参
y设置了参数默认值,故使用参数默认值2
x未设置参数默认值,故使用解构默认值1
2)fun({}, {});
给形参x,y,均传入空对象,故参数默认值不生效
x设置了解构默认值,解构默认值生效
y未设置解构默认值,空对象就是undefined,没有解构默认值可用
函数默认值
生效条件
不传参数
解构默认值
生效条件
1)不传参数
2)传undefined作为参数
即右边数组/对象成员严格等于(===)undefined时
const [a = 1, b = 2] = [3, 0];//a=3,b=0
const [a = 1, b = 2] = [3, null];//a=2,b=null
const [a = 1, b = 2] = [3];//a=3,b=2
默认值为表达式 ,表达式惰性求值
惰性求值:默认值生效后,才会调用执行表达式
例1:
const func = () => {
console.log('我被执行了');
return 2;
};
//默认值未生效,未调用func()
const [x = func()] = [1];//x=1
//默认值生效,调用func()
const [x = func()] = [];//x=2
## 参数默认值
# 设置默认值
```csharp
const [a = 1, b = 2] = [];
小技巧:
从参数列表右边开始设置参数的默认值
从左边
const multiply = (x = 1, y) => x * y;
// 调用时参数不能为空,得用undefined
console.log(multiply(undefined, 2));
从右边
const multiply = (x, y = 1) => x * y;
console.log(multiply(2));
注意:属性名是内置对象特有的,默认值是原型的属性/方法
1)一般属性为空,取到了undefined
const { a } ={};//undefined
2)toString属性为空,取到了原型的方法
const { toString } = {};//toString方法
应用-步步优化
1.传多参数
const LogUser = (username = 'ZhangSan ', age = 18, sex = 'male') =>
console.log(username, age, sex);
LogUser('Alex', 20, 'female');
问题:对应易混乱
2.用对象作参数优化
const LogUser = options =>
console.log(options.username, options.age,options.sex);
LogUser({
username: 'Alex',
age = 20,
sex = 'female'
})
问题:options出现次数过多
3.用解构优化
const LogUser = ({ username, age, sex }) =>
console.log(username, age, sex);
//调用函数
LogUser({
username: 'Alex',
age = 20,
sex = 'female'
})
//Alex 20 female
LogUser({ username: 'Alex' });
//Alex undefined undefined
LogUser({});
//undefined undefined undefined
LogUser();
//报错
4.设置解构默认值
const LogUser =
({ username = 'ZhangSan ', age = 18, sex = 'male' }) =>
console.log(username, age, sex);
LogUser({ username: 'Alex' });
//Alex 18 male
//{username = 'ZhangSan ', age = 18, sex = 'male'}=
//{ username: 'Alex' }
LogUser({});
//ZhangSan 18 male
// { username = 'ZhangSan ', age = 18, sex = 'male' }={ }
LogUser();
//报错,undefined不可解构赋值
// { username = 'ZhangSan ', age = 18, sex = 'male' }=undefined
问题:LogUser();//报错
5.手动解构参数
const LogUser =
({ username = 'ZhangSan ', age = 18, sex = 'male' } = {}) =>
console.log(username, age, sex);
LogUser();//ZhangSan 18 male
调用函数,会解构参数,参数直接变为
const LogUser =
(username = 'ZhangSan ', age = 18, sex = 'male' ) =>
console.log(username, age, sex);