本文为意译,非直译。具体解构赋值可以参考原文。解构赋值是javascript中的表达式语法糖,帮助开发者解构数组和对象属性,直接赋值给特定的变量。让a,b,rest;[a,b]=[10,20];console.log(a);//10,console.log(b);//20;[a,b,...rest]=[10,20,30,40,50,60];控制台日志(一);//10console.log(b);//20console.log(rest);//[30,40,50,60]简单练习,交互a和b的值让a=10,b=20;[a,b]=[b,a];console.log(a);//20console.log(b);//10;解构赋值数组对象解构赋值的具体用法//1.从已有的pair数组中解构赋值letfoo=['one','two','three'];let[a,b]=foo;console.log(a);console.log(b);//2.从字面量解构赋值let[a,b]=[1,2];//3.在解构时设置默认值赋值对让[a=5,b=10]=[1];console.log(a);//输出:1console.log(b);//output:10//4.解构从函数中返回pair数组functiongetArr(){return[1,2]}let[a,b]=getArr();//5.解构pair时,忽略特殊位置对值let[a,,b]=[1,2,3];//忽略所有[,,]=[1,2,3];//6.给数组的其他值赋值解构对时的变量let[a,...b]=[1,2,3,4,5];console.log(a);//1console.log(b);//[2,3,4,5]用于解构赋值的对象数据//1.解构对象letobj={name:'hello',age:18};let{name,age}=obj;console.log(name);//hello;console.log(age);//18//2.解构字面量对likeletname,age;({name,age}={name:'hello',age:18});//结果同上,注意这里为什么要用`()`包裹?//独立的写法let{name,age}={name:'hello',age:18};//3.解构时,设置别名letobj={name:'hello',age:18};let{name:nameA,age:ageA}=obj;console.log(nameA);//helloconsole.log(ageA);//18//4.设置默认值,这个类似于数组解构letobj={name:'hello',age:18};let{name='tom',age=20,city='sh'}=obj;console.log(city);//sh//5.设置默认值并设置别名letobj={n:'hello',age:18};let{n:name='tom',age:a=19,city:c='sh'}=obj;console.日志(名称);//helloconsole.log(a);//18console.log(c);//sh//6.设置函数参数默认值functiondrawES2015Chart({size='big',cords={x:0,y:0},radius=25}={}){console.log(size,线,半径);//绘制图表}drawES2015Chart({cords:{x:18,y:30},radius:30});embeddedSet对象解构和数组解构letdata={title:'objetAdnArray',list:[{id:1,des:'firstobject',proList:[]},{id:2,des:'secondobject',proList:[]}]}let{title,list:[{id,des}]}=数据;console.log(标题);//objetAdnArrayconsole.log(id);//1console.log(des);//第一个对象在forof循环中被解构varpeople=[{name:'MikeSmith',family:{mother:'JaneSmith',father:'HarrySmith',sister:'SamanthaSmith'},age:35},{name:'TomJones',family:{mother:'NorahJones',father:'RichardJones',brother:'HowardJones'},age:25}];for(let{name:n,family:{father:f}}ofpeople){console.log('Name:'+n+',Father:'+f);}//"姓名:MikeSmith,Father:HarrySmith"//"Name:TomJones,Father:RichardJones"解析对象的字段并将其传递给functionuserId({id}){returnid;}functionwhois({displayName,fullName:{firstName:名称}}){console.log(displayName+'is'+name);}varuser={id:42,displayName:'jdoe',fullName:{firstName:'John',lastName:'Doe'}};console.log('userId:'+userId(user));//"userId:42"whois(user);//"jdoeisJohn"将变量解构到keylet中key='z';let{[key]:foo}={z:'thisisz'};console.log(foo);//thisisz//注意thisuser和对象字面量赋值很像用法letobj={[key]:'hello'}obj.z//hello总结:es6提供了很多语法糖,需要在客户端使用时编译运行,nodejs在服务端已经很好的支持了
