ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值
解构是一种打破数据结构,将其拆分为更小部分的过程
let details = {
firstName:'Code',
lastName:'Burst',
age:22
}
//1、对象的解构赋值
const {firstName,age} = details;
console.log(firstName); // Code
console.log(age); // 22
//2、自定义变量名称
const {firstName:newname,age:newage} = details;
//3、运用解构赋值可以设置形参的默认值
const student = {
name:'Lily',
age:20,
scores:{
math:95,
chinese:98,
}
}
function showScore(student){
const { name,scores:{ math = 0,chinese = 0, english = 0}} = student;
console.log('学生名:' + name);
console.log('数学成绩:' + math);
console.log('语文成绩:' + chinese);
console.log('英语成绩:' + english);
}
showScore(student)
//学生名:Lily
//数学成绩:95
//语文成绩:98
//英语成绩:0
//数组的解构赋值
let arr=['Lily',18,'168cm']
let [name,age]=arr
console.log(name,age)
//按照顺序结构
let arr=['Lily',18,'168cm']
let [name,,high]=arr
console.log(name,high) //Lily 168cm
//同样,也可以设置默认值
let arr=['Lily',18,'168cm']
let [name,age,high,weight='45kg']=arr
console.log(name,age,high,weight) //Lily 18 168cm 45kg
//配合...扩展运算符
let colors = ['red','green','blue'];
let [firstColor,...otherColors] = colors;
console.log(firstColor); // red
console.log(otherColors); // ['green','blue']
let node = {
name:'foo',
loc:{
start:{
line:1,
column:1
}
},
range:[0,3]
}
let {
loc:{start:{line}},
range:[startIndex]
} = node;
console.log(line); // 1
console.log(startIndex); // 0
总结,使用场景:
1、设置函数形参的默认值
2、方便从 JSON 中提取数据,不再需要遍历整个解构了。