# Destructuring、Rest 與 Spread 運算

ES6 支援 Destructuring 的語法，它的概念像是模式比對（Pattern match）（然而不完全是），當你將某個結構拆解並分別指定給變數時，經常出現某種模式時，就可以使用這類語法。例如：

``````var scores = [80, 90, 99];
var score0 = scores[0];
var score1 = scores[1];
var score2 = scores[2];
``````

`scores` 的結果，可能來自某個函式傳回值，像這樣的例子，在 ES6 中可以寫成：

``````let scores = [80, 90, 99];
let [score0, score1, score2] = scores;
``````

``````> let [a, b, c] = 'XYZ';
undefined
> a;
'X'
> b;
'Y'
> c;
'Z'
>
``````

``````> let lt = [10, 9, 8, 7, 6];
undefined
> let [head, ...tail] = lt;
undefined
10
> tail;
[ 9, 8, 7, 6 ]
>
``````

Rest 運算 `...` 會將剩餘的元素迭代出來指定給 `tail`，這樣的話，寫函數式的程式碼就方便多了，來玩一下：

``````function sum(numbers) {
let [head, ...tail] = numbers;
return head + sum(tail);
} else {
return 0;
}
}

console.log(sum([1, 2, 3, 4, 5])); // 15
``````

``````function sum([head, ...tail]) {
return head ? head + sum(tail) : 0;
}

console.log(sum([1, 2, 3, 4, 5])); // 15
``````

``````let [a, b, c = 3] = [1, 2];
``````

``````> let [x, ,y, , z] = [1, 2, 3, 4, 5];
undefined
> x;
1
> y;
3
> z;
5
>
``````

``````> let [, ...tail] = [1, 2, 3, 4, 5];
undefined
> tail;
[ 2, 3, 4, 5 ]
>
``````

``````> let x = 10, y = 20;
undefined
> [x, y] = [y, x];
[ 20, 10 ]
> x;
20
> y;
10
>
``````

``````> let arr = [1, 2, 3];
undefined
> let arr2 = [...arr, 4, 5];
undefined
> arr2;
[ 1, 2, 3, 4, 5 ]
> function plus(a, b) {
...     return a + b;
... }
undefined
> plus(...[1, 2]);
3
>
``````

``````var o = {x : 10, y : 10};
var a = o.x;
var b = o.y;
``````

``````let o = {x : 10, y : 10};
let {x : a, y : b} = o;
``````

``````let o = {x : 10, y : 10};
let {x : a, y : b, z : c = 20} = o;
``````

``````let o = {x : 10, y : 10};
let {x : x, y : y} = o;
``````

``````let o = {x : 10, y : 10};
let {x, y} = o;
``````

``````let o = {x : 10, y : 10};
let {x, y, z = 10} = o;
``````

``````> function foo({x, y}) {
...     console.log(x);
...     console.log(y);
... }
undefined
>
> foo({x : 10, y : 10});
10
10
undefined
>
``````

``````let [[x, y, z], b, c] = [[1, 2, 3], 4, 5];
``````

``````let {a: {x, y, z}, b, c} = {a: {x: 10, y: 20, z: 30}, b: 40, c: 50};
``````