解構賦值讓我們能把一組變數與同結構的陣列或物件成員一一對應並賦值,寫法簡潔,是 ES6 裡使用頻率最高的語法之一。
let [a, b, c] = [1, 2, 3]; console.log(a); // 1 console.log([a, b, c]); // [1, 2, 3]
位置決定對應關係,因此順序必須一致。
巢狀結構同樣可以解構:
let [a, [b, [c]]] = [1, [2, [3]]]; console.log(c); // 3 let [d, , e] = [1, 2, 3]; // 中間留空可跳過 console.log(e); // 3 let [f, ...tail] = [1, 2, 3]; // 剩餘參數收集成陣列 console.log(tail); // [2, 3]
解構失敗時,變數會得到 undefined;而右邊元素多於左邊變數時,多出來的直接忽略,不會報錯。
let [a, b] = [1]; console.log(b); // undefined let [a2, b2, c2] = [1, 2, 3, 4]; console.log(c2); // 3
也可以指定預設值:
let [a = 1] = []; console.log(a); // 1 let [b = 1] = [2]; console.log(b); // 2 let [c = 1] = [undefined]; console.log(c); // 1 let [d = 1] = [null]; console.log(d); // null
最後一條是關鍵:ES6 使用嚴格相等運算子(===)判斷,只有值嚴格等於 undefined 時預設值才會生效,null 不會觸發。
預設值也可以是運算式,但要注意它是惰性求值的——只有在需要時才會被計算。
function f(){ alert(1); }
let [a = f()] = [3]; // f() 不會執行
let [b = f()] = [undefined]; // f() 會執行
把預設值寫成函數呼叫時,這個特性可以避免不必要的開銷。
let {foo, bar} = {foo: 1, bar: 2};
console.log(foo); // 1
與陣列最大的差異在這裡:物件解構不靠位置,而是靠屬性名匹配,因此順序無關。
let {bar: b, foo: f} = {foo: 1, bar: 2};
console.log(f); // 1
當變數名想與屬性名不同時,用冒號做重新命名:
let {first: f, last: l} = {first: 1, last: 3};
console.log(l); // 3
這裡 first 是匹配模式,f 才是真正的變數。因此完整形式是:
let {first: first, last: last} = {first: 1, last: 3};
物件解構也能巢狀:
let obj = { a: 1, b: ['hello', {c: 'world'}] };
let {a: a, b: [h, {c: w}]} = obj;
console.log(a, h, w); // 1 hello world
預設值與失敗處理:
let {x: x = 1, y: y = 2, z: z = 3, w: w} = {x: 3, y: null, z: undefined};
console.log(x); // 3
console.log(y); // null,同前/null 不觸發預設值
console.log(z); // 3
console.log(w); // undefined
字串能被解構,是因為此時它被轉成了類陣列的結構,可以依索引取值。
let [a, b, c] = 'hello'; console.log(a, b, c); // h e l
若等號右邊是數值或布林值,會先被包裝成對應的物件。
let {toString: s} = 123;
s === Number.prototype.toString; // true
let {toString: a} = true;
a === Boolean.prototype.toString; // true
規則可以歸納成一句:只要右邊不是物件或陣列,就先轉成物件。而 null 與 undefined 無法轉物件,因此對它們解構會直接報錯。
實務上最實用的場景有兩個:一是函數參數的具名化,把 function f(options) 改成 function f({width, height, ...rest}),呼叫端不必再記參數順序;二是接手 API 回應時直接取用巢狀欄位,省下大量中間變數。