当前位置: 首页 > Web前端 > HTML5

JS解构赋值

时间:2023-04-05 14:19:15 HTML5

从ES6开始,JavaScript引入了解构赋值,可以同时给一组变量赋值。.1.基本类型let[lString,lBoolean,lNumber]=['ES6',true,20181227];//Result:lString=ES6,lBoolean=true,lNumber=20181227/***注意解构赋值是在数组元素时,多个变量应该用[...]括起来。*如果数组本身是嵌套的,也可以通过下面的形式进行解构赋值。注意嵌套层次和位置要一致:*/let[lString,lBoolean,lNumber]=['ES6',[true,20181227]];//结果:lString=ES6,lBoolean=true,20181227,lNumber=undefined//正确的方法let[lString,[lBoolean,lNumber]]=['ES6',[true,20181227]];//result:lString=ES6,lBoolean=true,lNumber=20181227//解构赋值也可以忽略someelements:let[,,lNumber]=['ES6',[true,20181227]];//结果:lNumber=201812272数组类型let[clubs,players]=[['Lakers','Magic'],['LonzoBall','AnthonyDavis','KawhiLeonard','DonovanMitchell','DaronFox']];//Result:clubs=['Lakers','Magic']//Result:players=['LonzoBall','AnthonyDavis','KawhiLeonard','DonovanMitchell','DaronFox']3。ObjectTypeletperson={姓名:'DaronFox',年龄:20,性别:'男',护照:'G-12345678',学校:'肯德基',地址:{城市:'重庆',街道:'龙湖时代乐园街',zipcode:'400002'}};let{name,address:{city,zip}}=person;/***name='大龙狐狸'*city='重庆'*zip=undefined#因为属性名是zipcode而不是zip*注意:address不是变量,而是city和zip的嵌套地址对象的属性获取:*address;#ReferenceError:addressisnotdefined*//***>>当使用解构赋值给对象属性赋值时,如果对应的属性不存在,变量会被赋值为undefined,*这个是一致的withreferenceinganon-existingpropertygetundefined*>>如果要使用的变量名和属性名称不一致,可以使用如下语法获取:*/let{name,address:{city,zipcode:code}}=person;//code='400002'//默认值也可以用于解构赋值,避免了不存在的属性返回undefined的问题:let{name,address:{city,zipcode:code},club='kings'}=person;//club='kings'4.使用场景//快速获取当前页面域名和路径:let{hostname:domain,pathname:path}=location;/***如果一个函数接收一个对象作为参数,那么你可以使用解构直接将对象的属性绑定到变量上。*例如下面的函数可以快速创建一个Date对象:*/functionbuildDate({year,month,day,hour=0,minute=0,second=0}){returnnewDate(year+'-'+month+'-'+day+''+hour+':'+minute+':'+second);}buildDate({year:2018,month:12,day:27});//2018年12月27日星期四00:00:00GMT+0800(中国标准时间)//传入时分秒属性:buildDate({year:2018,month:12,day:27,hour:20,minute:15});//2018年12月27日星期四20:15:00GMT+0800(中国标准时间)