JavaScript ES6 Array and Object Destructuring Assignment 陣列和物件的解構賦值
ES6 的 destructuring assignment,可以用來從陣列或物件中抽取 (destructuring) 值出來指定 (assignment) 給變數。
Array Destructuring 陣列的解構賦值
在 ES6 之前,賦值給一個變量,只能用指定的方式:
const one = 'one';
const two = 'two';
const three = 'three';
ES6 你可以用 Destructuring 的語法:
const foo = ['one', 'two', 'three'];
// 從 array 中提取值,然後按照對應的位置,指定給相應的變數
const [one, two, three] = foo;
// "one"
console.log(one);
// "two"
console.log(two);
// "three"
console.log(three);
另外一個使用的例子:
function foo() {
return [1, 2, 3];
}
// [1, 2, 3]
const arr = foo();
const [a, b, c] = foo();
// 顯示 1 2 3
console.log(a, b, c);
也可以有預設值 (default value):
const [a = 5, b = 7] = [1];
// 1
console.log(a);
// 7
console.log(b);
可以留空來略過某些值:
function f() {
return [1, 2, 3];
}
// 跳過第二個值
const [a, , b] = f();
// 1
console.log(a);
// 3
console.log(b);
搭配 Rest Operator:
const [a, ...b] = [1, 2, 3];
// 1
console.log(a);
// [2, 3]
console.log(b);
Object Destructuring 物件的解構賦值
Destructuring 不僅可以用在 array,也可以用在 object:
const o = { p: 42, q: true };
// 從物件 o 中取出 key 為 p 和 q 的值,指定給變數 p 和 q
const { p, q } = o;
// 42
console.log(p);
// true
console.log(q);
也可以取值給已經宣告過的變數:
let a, b;
// 小括號 () 是必要的,不然左邊的 {} 會 SyntaxError 被當作是 block 區塊宣告
({ a, b } = { a: 1, b: 2 });
你的變數名稱可以和被取值的 object key 使用不同的名稱:
const o = { p: 42, q: true };
// 取出 key 名稱為 p 的值,指定給變數 foo
// 取出 key 名稱為 q 的值,指定給變數 bar
const { p: foo, q: bar } = o;
// 42
console.log(foo);
// true
console.log(bar);
也可以有預設值 (default value):
const { a = 10, b = 5 } = { a: 3 };
// 3
console.log(a);
// 5
console.log(b);
其實只要兩邊的結構 (patterns) 一樣,左邊的變數就會被賦予對應的值,所以用在 nested object 或 array 也行:
const obj = {
p: [
'Hello',
{
y: 'World',
},
],
};
const {
p: [x, { y }],
} = obj;
// "Hello"
console.log(x);
// "World"
console.log(y);
還可以用在函數的參數列上:
function drawES2015Chart({ size = 'big', cords = { x: 0, y: 0 }, radius = 25 } = {}) {
console.log(size, cords, radius);
}
// 輸出 big {x: 18, y: 30} 30
drawES2015Chart({
cords: { x: 18, y: 30 },
radius: 30,
});
上面的例子中 = {} 這語法是 ES6 新的 Default Function Parameters。
IE 最新版瀏覽器 IE11 目前還不支援 Destructuring。