让我们先回顾一下ES6的对象解构。本文介绍了ES6对象解构的各种用法。你用过哪一个?最基本的解构,提取对象中的一个字段constuser={id:123,name:'hehe'};const{名称}=用户;控制台日志(名称);//prints:hehe解构,有时使用别名接口定义的字段经常带下划线,但是我们的前端比驼峰式命名更好,所以你可以使用别名(重命名):constuser={id:123,nick_name:'呵呵'};const{nick_name:nickName}=user;console.log(nickName);//prints:hehe解构嵌套对象有时候我们会遇到嵌套对象,如果不够了解,我们会这样写解构:constuser={id:123,name:'hehe',education:{degree:'Masters'}};//假设我们要提取学位const{education}=user;const{degree}=教育;我们就写两行,一层层剥开,显然很麻烦,如果这个对象有三四层结构,根本看不出来。其实解构也可以一步到位:constuser={id:123,name:'hehe',education:{degree:'Masters'}};const{education:{degree}}=user;console.log(degree);//prints:Masters说的对,比别名方法多了一个{}。没有外层怎么办假设要解构的数据是接口返回的,由于某种原因会丢失某个字段。我们会经常遇到这种意外:constuser={id:123,name:'hehe'};const{教育:{学位}}=用户;//TypeError:无法匹配'undefined'或'null'。这时候你是不是觉得我们原来的方法还好用:consteducation=user||{};数据防御的目的,告别冗长的写法:constuser={id:123,name:'hehe'};const{教育:{学位}={}}=用户;控制台日志(度数);//prints:undefined这显然是一个清晰的流。更深的物体呢?constuser={id:123,name:'呵呵'};const{教育:{学校:{姓名}}={}}=用户;//TypeError:无法匹配'undefined'或'null'。这里外面的图层设置了教育的默认值,但是里面的学校是不存在的,还是会报错。我们第一个方法是继续设置school的默认值为{}:constuser={id:123,name:'hehe'};const{教育:{学校:{名称}={}}={}}=用户;console.log(名称);//prints:undefined另一种方式是直接将education的默认值设为{school:{}}:constuser={id:123,name:'hehe'};const{education:{school:{name}}={school:{}}}=user;console.log(name);//prints:undefined这两个方法貌似可以,但是如果要给学校起个名字school给.name一个默认值呢?如果是第一种方法,会这样写:constuser={id:123,name:'hehe'};const{education:{school:{name='NB'}={}}={}}=user;console.log(name);//prints:注意,有多少个“=”符号?太啰嗦了,看第二种方法:constuser={id:123,name:'hehe'};const{education:{school:{name}}={school:{name:'NB'}}}=user;console.log(name);//prints:NB为教育整体设置一个默认值,这样可读性更强,这又是一个cleanstream。在代码中灵活运用解构,不仅可以使代码简洁易读,而且风格上也有很大的提升。
