结构赋值:在日常开发中,我们经常会定义很多的数组或者对象,然后从数组或对象中提取出相关的信息,通常这样写代码会显得很凌乱,通过结构赋值可以大大简化了写代码的量。
下面我们来看一些例子来学习一下:
例子1:
const student = {
name:'jsPool',
age:20,
}
要取到name,和age的值,常规写法:
console.log(student.name) //"jsPool"
console.log(student.age) //20
es6写法
结构赋值
const {name,age}=student
console.log(name)//"jsPool"
console.log(age)//20
例子2:
const student = {
scores:{
math:95,
chinese:98,
english:93
}
}
常规写法:
console.log(student.scores.math)//95
console.log(student.scores.chinese)//98
console.log(student.scores.english)//93
上面的常规写法,可以实现,但出现了好多重复的代码比如前面的student.scores,来看一下es6的写法,因为是
两层的花括号,通过解构赋值也是可以实现的
const {scores:{math,chinese,english}}=student
console.log(math)//95
console.log(chinese)//98
console.log(english)//93
上面是一些常规的解构赋值的方法,同样数组,混合类型都可以像上面那样进行解构赋值,今天就分享到这了,谢谢大家。