Deconstruction of objects is a concise syntax that assigns object properties and methods to a series of variables in quick batches
Basic syntax:
1.赋值运算符 = 左侧的 {} 用于批量声明变量,右侧对象的属性值将被赋值给左侧的变量
2. The value of the object attribute will be assigned to the variable with the same attribute name
3. Note that the deconstructed variable name should not conflict with the external variable name, or an error will be reported
4. When the attribute consistent with the variable name cannot be found in the object, the variable value is undefined
Deconstructive grammar
const obj={ uname:'程序员', age:18 } const {uname,age} = {uname:'程序员',age:18} console.log(uname)//uname='程序员' console.log(age)//age=18
The variable name of object deconstruction can be renamed old variable name: new variable name
const {uname:username,age} = {uname:'程序员',age:18} console.log(username)//username='程序员' console.log(age)//age=18
Deconstruct Array Object
const pig=[{ uname:'佩奇', age:20 }] const [{uname,age}]=pig console.log(uname)//uname='佩奇' console.log(age)//age=20
Multi level object deconstruction
const pig={ name:'佩奇', family:{ mother:'猪妈妈', father:'猪爸爸', brother:'乔治' }, age:16 } const {name,family:{mother,father,brother}}=pig console.log(name)//name='佩奇' console.log(mother)//mother='猪妈妈' console.log(father)//father='猪爸爸' console.log(brother)//brother='乔治'