欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ECMAScript6--解構(gòu)

 更新時(shí)間:2017年03月30日 08:59:35   作者:老板丶魚丸粗面  
解構(gòu)就是將聲明的一組變量和與相同結(jié)構(gòu)的數(shù)組或者對(duì)象的元素?cái)?shù)值一一對(duì)應(yīng),并將變量相對(duì)應(yīng)元素進(jìn)行賦值。本文將詳細(xì)介紹ECMAScript6--解構(gòu)的相關(guān)知識(shí)。下面跟著小編一起來看下吧

大致介紹

解構(gòu):就是將聲明的一組變量和與相同結(jié)構(gòu)的數(shù)組或者對(duì)象的元素?cái)?shù)值一一對(duì)應(yīng),并將變量相對(duì)應(yīng)元素進(jìn)行賦值

數(shù)組解構(gòu)

例子:

 let [a,b,c] = [1,2,3];
 console.log(a); //1
 console.log([a,b,c]); //[1, 2, 3]

可以看到,數(shù)組中的a,b,c分別對(duì)應(yīng)1,2,3

嵌套的數(shù)組也可以進(jìn)行解構(gòu)

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]

在解構(gòu)不成功時(shí),變量的值就是undefined

 let [a,b] = [1];
 console.log(b); //undefined

不完全解構(gòu)也是可以的

 let [a,b,c] = [1,2,3,4];
 console.log(c); //3

也可以設(shè)置默認(rèn)值

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中使用嚴(yán)格相等運(yùn)算符(===)。所以如果默認(rèn)值不嚴(yán)格相等undefined,默認(rèn)值就不會(huì)生效。例如null

默認(rèn)值也可以是表達(dá)式,但是要注意只有默認(rèn)值在使用時(shí)才會(huì)觸發(fā)函數(shù)(惰性求值)

function f(){
  alert(1);
 }
 let [a = f()] = [3]; //f()不會(huì)執(zhí)行
 let [b = f()] = [undefined]; //會(huì)執(zhí)行

對(duì)象解構(gòu)

例子:

 let {foo,bar} = {foo:1,bar:2};
 console.log(foo); //1

注意:與數(shù)組不同,對(duì)象解構(gòu)時(shí)不是根據(jù)位置對(duì)變量賦值的,而是通過變量名進(jìn)行賦值,即變量名和屬性名必須相等才可以進(jìn)行賦值,位置不重要

 let {bar,foo} = {foo:1,bar:2};
 console.log(foo);//1

如果變量名和屬性名不相同,則要采取下面的方法

 let {first: f,last: l} = {first:1,last:3};
 console.log(l); //3

意思就是先在對(duì)象中查找first屬性,如果有就賦值給f,其中first是匹配的模式,而f才是真正的變量

所以對(duì)象解構(gòu)的完整形式是:

let {first: first,last: last} = {first:1,last:3}; 

對(duì)象解構(gòu)也可以進(jìn)行嵌套

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

對(duì)象解構(gòu)也可以設(shè)置默認(rèn)值,并且如果解構(gòu)失敗,變量會(huì)賦值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 

字符串解構(gòu)

字符串之所以能夠解構(gòu)是因?yàn)榇藭r(shí)字符串轉(zhuǎn)換成了一個(gè)數(shù)組

 let [a,b,c] = 'hello';
 console.log(a); //h
 console.log(b); //e
 console.log(c); //l

數(shù)值和布爾值解構(gòu)

解構(gòu)賦值時(shí),如果等號(hào)右邊是數(shù)值和布爾值,則會(huì)先轉(zhuǎn)為對(duì)象

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: a} = true;
a === Boolean.prototype.toString // true

上面代碼中,數(shù)值和布爾值的包裝對(duì)象都有tostring屬性,因此變量s都能取到值。

解構(gòu)賦值的規(guī)則是,只要等號(hào)右邊的值不是對(duì)象或數(shù)組,就先將其轉(zhuǎn)為對(duì)象。由于null和undefined無法轉(zhuǎn)為對(duì)象,所以對(duì)它們進(jìn)行解構(gòu)賦值,都會(huì)報(bào)錯(cuò)。

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

最新評(píng)論