<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>对象解构</title> </head> <body> <script> let person = { name:'gpl', age:33 }; //一般的写法:对象解构赋值,属性名和对象对应,属性值是新变量名 let {name:p1Name,age:p1Age} = person; console.log(p1Name); //gpl console.log(p1Age); //33 //简洁的写法:直接使用对象的属性名作为变量名 let {name,age} = person; console.log(name); //gpl console.log(age); //33 //错误的写法 let {p2name,p2age} = person; console.log(p2name); //undefined console.log(p2age); //undefined let person2 = { name2:'fbb', age2:38 }; //新变量不需要和属性一一对应 // let {name2} = person2; // console.log(name2); //fbb // // let {age2} = person2; // console.log(age2); //38 // let {age2,name2} = person2; // console.log(name2); //fbb // console.log(age2); //38 // let {name2,job = 'female'} = person2; // console.log(name2,job); //fbb female // // let {name3,age3} = {name3:'lzl',age3:40}; // console.log(name3,age3); //解构在内部使用函数ToObject()把原数据解构转换为对象,也就是原始值会被当成对象 //下面的length是字符串'foobar'转换为对象之后的自带属性 let {length} = 'foobar'; console.log(length); //6 //没有ddd这个属性 let {ddd} = 'foobar'; console.log(ddd); //undefined let{constructor:c} = 4; console.log(c); //数字4对象之后的构造函数 console.log(c === Number); //true //根据ToObject()的定义,null和undefined不能被解构 // let {_} = null; //TypeError // // let {_} = undefined; //TypeError //不要求新变量必须在表达式中声明,但如果是给事先声明的变量赋值,则赋值表达式必须包含在一对括号中 let person3 = { name:'gadot', age:37 }; let p4name,p4age; ({name:p4name,age:p4age} = person3); //表达式必须包含在括号里,否则会报错 console.log(p4name,p4age); </script> </body> </html>
标签:console,log,对象,解构,let,name2,name From: https://www.cnblogs.com/polin/p/17134539.html