### 解構
* 數組的解構賦值
* 對象的解構賦值
* 字符串的解構賦值
* * * * *
#### 數組的解構賦值
> 在ES5中為變量賦值語法如下:
~~~
var i = 0
~~~
> ES6中允許如下寫法:
~~~
let [ i , y ] = [ 1 , 2 ]
console.log(i) //1
console.log(y) //2
~~~
> 上面代碼表示,可以從數組中提取值,按照對應位置,對變量賦值。
>本質上,這種寫法屬于“模式匹配”,只要等號兩邊的模式相同,左邊的變量就會被賦予對應的值。下面是一些使用嵌套數組進行解構的例子。
>解構賦值的規則是:***只要等號右邊的值不是對象,就先將其轉為對象,然后再進行賦值操作。***
~~~
let [bar, foo] = [1];
console.log(bar) //1
console.log(foo) //undefined
~~~
> 如上代碼所示,如果解構不成功,變量的值就等于undefined。如果等號的右邊不是數組(或者嚴格地說,不是可遍歷的結構),那么將會報錯。
~~~
let [x, y] = [1, 2, 3];
console.log(x) // 1
console.log(y) // 2
let [a, [b], d] = [1, [2, 3], 4];
console.log(a) // 1
console.log(b) // 2
console.log(d) // 4
~~~
> 上面兩種情況屬于不完全解構,但是可以成功。
> 同時你也可以在解構操作中為變量添加默認值。
~~~
let [x = 1, y = x] = [];
console.log(x) //1
console.log(y) //1
let [x = 1, y = x] = [2];
console.log(x) //2
console.log(y) //2
let [x = 1, y = x] = [1, 2];
console.log(x) //1
console.log(y) //2
let [x = y, y = 1] = [];
console.log(x) // ReferenceError
~~~
> 上面最后一個表達式之所以會報錯,是因為x用到默認值y時,y還沒有聲明。
* * * * *
#### 對象的解構賦值
~~~
let { foo, bar } = { foo: "aaa", bar: "bbb" };
console.log(foo) // "aaa"
console.log(bar) // "bbb"
~~~
> 對象的解構與數組有一個重要的不同。數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
#### 字符串解構
> 字符串也可以解構賦值。這是因為此時,字符串被轉換成了一個類似數組的對象。
~~~
const [a, b, c, d, e] = 'hello';
console.log(a) // "h"
console.log(b) // "e"
console.log(c) // "l"
console.log(d) // "l"
console.log(e) // "o"
~~~
> 類似數組的對象都有一個length屬性,因此還可以對這個屬性解構賦值。
~~~
let {length : len} = 'hello';
console.log(len) // 5
~~~