帝王谷资源网 Design By www.wdxyy.com
大致介绍
解构:就是将声明的一组变量和与相同结构的数组或者对象的元素数值一一对应,并将变量相对应元素进行赋值
数组解构
例子:
let [a,b,c] = [1,2,3]; console.log(a); //1 console.log([a,b,c]); //[1, 2, 3]
可以看到,数组中的a,b,c分别对应1,2,3
嵌套的数组也可以进行解构
let [a,[b,[c]]] = [1,[2,[3]]]; console.log(c); //3 let [d,,e] = [1,2,3]; console.log(e); //3 let [f,...tail] = [1,2,3]; console.log(tail); //[2, 3]
在解构不成功时,变量的值就是undefined
let [a,b] = [1]; console.log(b); //undefined
不完全解构也是可以的
let [a,b,c] = [1,2,3,4]; console.log(c); //3
也可以设置默认值
let [a = 1] = []; console.log(a); //1 let [b = 1] = [2]; console.log(b); //2 let [c = 1] = [undefined]; console.log(c); //1 let [d = 1] = [null]; console.log(d); //null
注意:在ES6中使用严格相等运算符(===)。所以如果默认值不严格相等undefined,默认值就不会生效。例如null
默认值也可以是表达式,但是要注意只有默认值在使用时才会触发函数(惰性求值)
function f(){ alert(1); } let [a = f()] = [3]; //f()不会执行 let [b = f()] = [undefined]; //会执行
对象解构
例子:
let {foo,bar} = {foo:1,bar:2}; console.log(foo); //1
注意:与数组不同,对象解构时不是根据位置对变量赋值的,而是通过变量名进行赋值,即变量名和属性名必须相等才可以进行赋值,位置不重要
let {bar,foo} = {foo:1,bar:2}; console.log(foo);//1
如果变量名和属性名不相同,则要采取下面的方法
let {first: f,last: l} = {first:1,last:3}; console.log(l); //3
意思就是先在对象中查找first属性,如果有就赋值给f,其中first是匹配的模式,而f才是真正的变量
所以对象解构的完整形式是:
let {first: first,last: last} = {first:1,last:3};
对象解构也可以进行嵌套
let obj = { a:1, b:[ 'hello', {c:'world'} ] } let {a: a,b: [h,{c:w}]} = obj; console.log(a); //1 console.log(h); //hello console.log(w); //world
对象解构也可以设置默认值,并且如果解构失败,变量会赋值undefined
let {x: x = 1,y: y=2,z: z=3,w: w} = {x:3,y:null,z:undefined}; console.log(x) //3 console.log(y) //null console.log(z) //3 console.log(w) //undefined
字符串解构
字符串之所以能够解构是因为此时字符串转换成了一个数组
let [a,b,c] = 'hello'; console.log(a); //h console.log(b); //e console.log(c); //l
数值和布尔值解构
解构赋值时,如果等号右边是数值和布尔值,则会先转为对象
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: a} = true; a === Boolean.prototype.toString // true
上面代码中,数值和布尔值的包装对象都有tostring属性,因此变量s都能取到值。
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于null和undefined无法转为对象,所以对它们进行解构赋值,都会报错。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
标签:
ecmascript6
帝王谷资源网 Design By www.wdxyy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
帝王谷资源网 Design By www.wdxyy.com
暂无评论...
更新日志
2024年10月25日
2024年10月25日
- 群星2013-青春缤纷辑压箱宝大公开3CD2[新加坡限量版][WAV整轨]
- 林育群.2013-BalladShow(日本版)【环球】【WAV+CUE】
- 陈加洛.1992-痛到感觉不到【宝丽金】【WAV+CUE】
- 群星.2023-宿命之敌电视剧原声带【韶愔音乐】【FLAC分轨】
- 東京事変-大発見[FLAC+CUE]
- 椎名林檎-三文ゴシップ[FLAC+CUE]
- 2024年08月04日
- 裘德《裘德「最后的水族馆」演唱会LIVE》[320K/MP3][228.89MB]
- 裘德《裘德「最后的水族馆」演唱会LIVE》[24bit 48kHz][FLAC/分轨][2.08G]
- 基因三重奏《如果你什么都不说 音乐会现场录音》[320K/MP3][145.37MB]
- 孟庭苇.1996-月亮说话(2020环球24KGOLD限量版)【上华】【WAV+CUE】
- 群星.1997-新艺宝优质音响系列·国语精选监听版【新艺宝】【WAV+CUE】
- 阿桑.2005-寂寞在唱歌(星外星引进版)【华研国际】【WAV+CUE】
- 基因三重奏《如果你什么都不说 音乐会现场录音》[FLAC/分轨][287.43MB]
- 蔡题谦《我爱你,却依然要看你走》[320K/MP3][88.65MB]