栗子
先来看一个解构赋值的例子:
let uesr = {
name: 'wenyue',
age:20,
}
let { name, age } = user;
console.log(name); //wenyue
console.log(age); //20
user.name的值存储到变量name中,user.age的值呗存储到变量age中。
设置默认值
let uesr = {
name: 'wenyue',
}
let { name, age } = user;
console.log(name); //wenyue
console.log(age); //undefined
如果指定的局部变量名在对象中不存在,则赋值为undefined。
let uesr = {
name: 'wenyue',
}
let { name, age = 1 } = user;
console.log(name); //wenyue
console.log(age); //1
通过在属性名称后添加一个等号(=)和相应的默认值,设置默认值。
为非同名的变量赋值
let uesr = {
name: 'wenyue',
age: 20,
}
let { name: username, age: userage } = user;
console.log(username); //wenyue
console.log(userage); //20