ECMAScript6--解構(gòu)
大致介紹
解構(gòu):就是將聲明的一組變量和與相同結(jié)構(gòu)的數(shù)組或者對象的元素數(shù)值一一對應(yīng),并將變量相對應(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分別對應(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)不成功時,變量的值就是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)格相等運算符(===)。所以如果默認(rèn)值不嚴(yán)格相等undefined,默認(rèn)值就不會生效。例如null
默認(rèn)值也可以是表達(dá)式,但是要注意只有默認(rèn)值在使用時才會觸發(fā)函數(shù)(惰性求值)
function f(){
alert(1);
}
let [a = f()] = [3]; //f()不會執(zhí)行
let [b = f()] = [undefined]; //會執(zhí)行
對象解構(gòu)
例子:
let {foo,bar} = {foo:1,bar:2};
console.log(foo); //1
注意:與數(shù)組不同,對象解構(gòu)時不是根據(jù)位置對變量賦值的,而是通過變量名進(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
意思就是先在對象中查找first屬性,如果有就賦值給f,其中first是匹配的模式,而f才是真正的變量
所以對象解構(gòu)的完整形式是:
let {first: first,last: last} = {first:1,last:3};
對象解構(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
對象解構(gòu)也可以設(shè)置默認(rèn)值,并且如果解構(gòu)失敗,變量會賦值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)是因為此時字符串轉(zhuǎn)換成了一個數(shù)組
let [a,b,c] = 'hello'; console.log(a); //h console.log(b); //e console.log(c); //l
數(shù)值和布爾值解構(gòu)
解構(gòu)賦值時,如果等號右邊是數(shù)值和布爾值,則會先轉(zhuǎn)為對象
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: a} = true;
a === Boolean.prototype.toString // true
上面代碼中,數(shù)值和布爾值的包裝對象都有tostring屬性,因此變量s都能取到值。
解構(gòu)賦值的規(guī)則是,只要等號右邊的值不是對象或數(shù)組,就先將其轉(zhuǎn)為對象。由于null和undefined無法轉(zhuǎn)為對象,所以對它們進(jìn)行解構(gòu)賦值,都會報錯。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Javascript實現(xiàn)的類似Google的Div拖動效果代碼
Javascript實現(xiàn)的類似Google的Div拖動效果代碼,需要的朋友可以參考下。2011-08-08
詳解promise.then,process.nextTick, setTimeout 以及 setImmediate的
這篇文章主要介紹了詳解promise.then,process.nextTick, setTimeout 以及 setImmediate的執(zhí)行順序2018-11-11
JS實現(xiàn)的獲取銀行卡號歸屬地及銀行卡類型操作示例
這篇文章主要介紹了JS實現(xiàn)的獲取銀行卡號歸屬地及銀行卡類型操作,結(jié)合實例形式分析了javascript不依賴第三方接口計算銀行卡歸屬地相關(guān)信息操作技巧,需要的朋友可以參考下2019-01-01
Webpack設(shè)置環(huán)境變量的一些誤區(qū)詳解
這篇文章主要給大家介紹了關(guān)于Webpack設(shè)置環(huán)境變量的一些誤區(qū),文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Webpack具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

