[JS] ES6 中的陣列解構賦值(array destructuring)
在 ES6 中過去的陣列和物件可以透過解構(destructuring)的 方式來賦值。這篇文章中,我們會先說明如何透過陣列的方式來賦值。
陣列解構賦值的方法(array destructuring)
過去陣列內的元素在賦值的時候,只能透過直接給值的方式,像是下面這樣:
let numbers = [1, 2, 3];
let a = numbers[0];
let b = numbers[1];
let c = numbers[2];
console.log(a, b, c); // 1, 2, 3
一般用法
然而在 ES6 中可以直接透過解構的方式賦值,像是下面這樣子:
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1, 2, 3