陣列

陣列解構 在 JavaScript

1 個練習

關於 陣列解構

陣列解構賦值是一種從陣列中擷取值的簡潔寫法。它的語法類似陣列實字運算式,差別在於它位於賦值運算式的左邊,而不是右邊。

const frenchNumbers = ['quatre-vingts', 'quatre-vingt-dix', 'cent'];
const [french80, french90, french100] = frenchNumbers;

french80;
// => 'quatre-vingts'
french90;
// => 'quatre-vingt-dix'
french100;
// => 'cent'

重新賦值

由於變數是依照位置對應到陣列中的值,因此解構語法可以在單一運算式中指定或重新指定多個變數。

let [a, b] = ['world', 'hello'];
[b, a] = [a, b];

a;
// => 'hello'
b;
// => 'world'

巢狀陣列也適用。

let [a, b, c] = ['orange', 'purple', 'green'];
[[a, b], c] = [[c, a], b];

a;
// => 'green'
b;
// => 'orange'
c;
// => 'purple'

略過賦值

解構語法允許在對應時略過某些值,例如忽略陣列中的特定位置。 在下面的範例中,假設有一個 getUserInfo 函式,它會回傳一個包含使用者名字、姓氏和街道地址的陣列。

getUserInfo();
// => ["Valerie", "Noir", "Sunny Lane 523"]

const [, , streetAddress] = getUserInfo();

streetAddress;
// => "Sunny Lane 523"

捨棄部分值

賦值時也不一定要用到所有的值。

const [firstName, lastName] = getUserInfo();

firstName;
// => "Valerie"

lastName;
// => "Noir"

取得比實際更多的值

甚至可以取出比陣列中還多的值;剩下的變數會被指定為 undefined。當值的數量無法事先得知時,這可能會很有用。

const pickAtLeastOne = ['first choice', 'second choice'];
const [first, second, third, fourth] = pickAtLeastOne;

first;
// => "first choice"

second;
// => "second choice"

third;
// => undefined

fourth;
// => undefined

預設值

陣列解構賦值可以提供預設值,以防來源陣列中沒有對應的值。

const [first, second, third = 'none selected', fourth] = pickAtLeastOne;

third;
// => 'none selected'

fourth;
// => undefined

相關概念

object-destructuring rest-and-spread

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 陣列解構