陣列解構

在ES5的寫法中,如果我們要取出物件的屬性都某個變數中,可能會這樣寫

var nums = [120,325,135];
var first = nums[0];
var second = nums[1];

在ES6我們可以改成這樣:

const nums = [120,325,135];
let first;
let second;
[first,second] = nums;

非常奇怪的寫法,但如果這樣寫:

[first,second] = nums;

這樣視同:

 first = nums[0];
 second = nums[1];

可以理解成這樣:

宣告 陣列 = [值,值,值];
宣告 變數1;
宣告 變數2;
[變數1,變數2] = 陣列;

如此一來陣列會解構出對應的值並賦值給變數,以上面例子來說改成這樣

const nums = [120,325,135];
let first;
let second;
let third;
[first,second,third] = nums;
  • first被賦值 nums 陣列[0] 的120
  • second被賦值 nums 陣列[1] 的325
  • third被賦值 nums 陣列[2] 的135

那如果多加一個 forth 呢?

const nums = [120,325,135];
let first;
let second;
let third;
let forth;
[first,second,third,forth] = nums;

這樣寫不會報錯,但因為解構的陣列沒有對應 forth 的第四個陣列值,所以 forth 會是 undefined。

如果嫌變數一個一個宣告很麻煩,也可以改成這樣

const nums = [120,325,135];
let [first,second,third,forth] = nums;

結果也是一樣的!

預設值

透過這種寫法,我們還可以給陣列設定預設值,例如

const nums = [120,325];
let [first,second,third] = nums;

因為third對應nums陣列第三個值,但nums陣列現在只有兩個數值,所以third會是undefined但是,我們可以這樣寫:

const nums = [120,325];
let [first,second,third=100] = nums;

這麼一來,third就會是100囉!

忽略元素

如果我們只想取出陣列第二個內容,不想取出陣列第一個內容,可以透過這種寫法達成這個目的嗎?可以這樣寫

const nums = [120,325,135];
let [,second] = nums;

[ ] 內用逗號分隔變數,第一個120不想取出來,所以留空就好,用,分隔,第二個變數 second 就會取到 nums 的第二個值。

也就是說這樣視同:

let second = nums[1]

那如果想取陣列第三個內容呢?

一樣用逗號隔開變數,不想取的就留空:

const nums = [120,325,135];
let [,,third] = nums;

這樣視同

let third = nums[2]

變數交換

以往ES5變數交換是這樣寫:

var a = 100;
var b = 50;
var c;

c = a;
a = b;
b = c;

用第三個變數c當成暫存,儲存a變數的值,現在利用ES6解構賦值,有更乾淨的寫法:

let a = 100;
let b = 50;
[a,b] = [b,a]

這樣就不用宣告第三個變數囉!

剩餘部分(...運算子)

... 運算子在 ES6+很常看到,那它的功用是什麼呢?

const nums = [123,456,0,666];
const [first,...others] = nums;

上述程式碼,透過陣列解構的概念,可以知道現在變數first是123,其餘的陣列內容,會對應「...」運算子,被扔進另一個陣列保存。

「...」後面接的變數名,會創造這個變數並指向一個陣列,而這個陣列的內容就是陣列解構中,剩下來的陣列內容,例如:

others 陣列保存了剩下的部分 [ 456, 0, 666 ],如果想保存 [ 0 , 666 ] 而已,可以這樣寫:

const nums = [123,456,0,666];
const [first,second,...others] = nums;

first 對應 123、second 對應456,而others 就是 [0,666] 啦!