插個旗子🚩記念一番,這是ES6的第一篇文章( ̄︶ ̄)↗ 。javascript
ECMAScript是一種腳本語言的標準規範,ES6(ECMAScript)於2015正式發佈。java
ECMAScript (or ES) is a scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript, so as to foster multiple independent implementations. ——《維基百科》數組
ES6中,可使用數組和對象對變量賦值,叫作「解構賦值」。函數
解構賦值能夠分爲:數組的解構賦值、對象的解構賦值。ui
解構賦值清晰又簡潔,優雅又有效率。是不可多得的「賦值利器」。spa
let arr =[1,2,5];
let [a,b,c]=arr;
console.log([a,b,c]);
複製代碼
對應關係是這樣滴:3d
let arr =[1,2,5,6];
let [a,b,c]=arr;
console.log([a,b,c]);
複製代碼
多餘的會被忽略掉。code
let arr =[1,2];
let [a,b,c]=arr;
console.log([a,b,c]);
複製代碼
少的會undefined。cdn
let arr =[1,2,3];
let [a,,c]=arr;
console.log([a,,c]);
複製代碼
對應關係是這樣滴:對象
let a={
first:1,
second:2
}
let {first,second}=a;
console.log({first,second})
複製代碼
按屬性名的一一對應關係來賦值:
let a={
first:1
}
let {first,second}=a;
console.log({first,second})
複製代碼
找不到的屬性會undefined。
let a={
one:1,
two:2
}
let {first,second}=a;
console.log({first,second})
複製代碼
let a={
second:2,
first:1
}
let {first,second}=a;
console.log({first,second})
複製代碼
由於對象是元素的無序集合,因此順序有並無影響。
如{first=10,second}
。
原來咱們若是要交換兩個變量的值,須要這麼搞:
let a=1;
let b=2;
let c;
c=a;
a=b;
b=c;
console.log(a);
console.log(b);
複製代碼
呃,有效但頗爲繁瑣......
可是,有了解構賦值後:
let a=1;
let b=2;
[a,b]=[b,a]
console.log(a);
console.log(b);
複製代碼
原來咱們寫個函數,若是參數較多時,實參萬一寫錯一個,就一步錯,步步錯:
function f(a,c,b,d,e,f,g){
console.log(a,b,c,d,e,f,g)
}
f("one","two","three","four","five","six","seven")
複製代碼
可是如今,咱們有了賦值利器——解構賦值:
function f({a,c,b,d,e,f,g}){
console.log(a,b,c,d,e,f,g)
}
f({a:"one",b:"two",c:"three",d:"four",e:"five",f:"six",g:"seven"})
複製代碼
清晰明瞭,想出錯都難。
嗯,優雅~~
。
。
。
解構賦值在實際中應用還有不少。。。。。。
本文對解構賦值作了簡要總結,解構賦值應用普遍,本篇所述內容皮毛而已,但願有所幫助。