ES6學習——新的語法:陣列解構(Array Destructuring)
阿新 • • 發佈:2019-01-23
上一篇文章講了Object的解構,這篇講一下Array的解構,概念大同小異,只是寫法會有一些不同,先看個簡單的例子:
let [x, y] = ['a', 'b','c']; // x = 'a'; y = 'b'
跟物件解構一樣,先探討一下賦值表示式的右側應具備什麼條件才能進行解構賦值,規範的12.14.5.2有這樣的描述:
ArrayAssignmentPattern : [ ]
1. Let iterator be GetIterator(value).
2. ReturnIfAbrupt(iterator).
3. Return IteratorClose(iterator, NormalCompletion(empty )).
從上面的描述看,右側應該是個iterator物件,具體什麼樣的物件才能算是iterator,後面章節會詳細講,這裡就不仔細說了,先記住就好了。
let x;
[x] = {}; // TypeError, empty objects are not iterable
[x] = undefined; // TypeError, not iterable
[x] = null; // TypeError, not iterable
上面的例子說明了物件,undefined,null不是iterator物件。
下面看一些陣列解構的特性:
let [x] = []; // x = undefined var o = {},a =[]; [o.a, o.b, o.c,a[0]] = [1,2,3,4]; //o:{ a: 1, b: 2, c: 3 },a:[4] let [x,...y] = 'abc'; // x='a'; y=['b', 'c'],rest操作符 var o = [1,2,3], a, b, c, p; p = [,,c] = [a,b] = o;//解構連續賦值 trace( a + " " + b + " " +c ); // 1 2 3 trace(p === o); // true var a1 = [ 1, [2, 3, 4,7,8], 5 ];//巢狀解構+rest操作符 var [ a, [ b, c,...d], e ] = a1; //a=1,b=2,c=3,d=[4,7,8],e=5
下面看一下如何用陣列解構交換兩個變數的值:
var x = 10, y = 20;
[ y, x ] = [ x, y ];//如此的優雅
//如果還藉助臨時變數,還可以用異或操作符,當然不好理解
x^=y;
y^=x;
x^=y;
在物件解構的時候有預設值的使用,同樣陣列解構也可以有預設值:
let [{ prop: x } = { prop: 123 }] = [];//x=123let [x=3, y] = []; // x = 3; y = undefined let [x=1] = [undefined]; // x = 1 function log(x) { trace(x+"\n"); return 'YES' } let [a=log('hello')] = [1];//a = 1 let [a=log('hello')] = [0];//a = 'YES',注意這裡Kinoma和ES6規範的區別,在Firefox43下,a=0 let [x=3, y=x] = []; // x=3; y=3 let [x=3, y=x] = [7]; // x=7; y=7 let [x=3, y=x] = [7, 2]; // x=7; y=2 let [x=y, y=3] = []; // ReferenceError,從左到右evaluate let [{ prop: x } = {}] = [];//x=undefined let [{ prop: x } = {}] = [1];//x=undefined
let [{ prop: x } = { prop: 123 }] = [{prop:1}];//x=1
介紹完了上面這些特性,下面看個實際使用中的例子:
let [all, year, month, day] =/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('2015-12-31');
//all="2015-12-31",year="2015",month="12",day="31"
let [, , , day] =/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec("test") || [];
//day=undefined,如果不寫||[],將會報錯,因為exec返回null,而null是不能進行解構的
*以上全部程式碼在Kinoma Studio中通過測試