1. 程式人生 > >【ES6】陣列解構賦值

【ES6】陣列解構賦值

1. 陣列的解構賦值

基本用法

ES6 允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為解構(Destructuring)。

// ES5
let a = 1;
let b = 2;
let c = 3;
// ES6
let [a, b, c] = [1, 2, 3]

本質上,這種寫法屬於“模式匹配”,只要等號兩邊的模式相同,左邊的變數就會被賦予對應的值。下面是一些使用巢狀陣列進行解構的例子。

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third]
= ["foo", "bar", "baz"]; third // "baz" let [x, , y] = [1, 2, 3]; x // 1 y // 3 // Rest 元素必須是最後一個元素(...name) let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] let [x, y, ...z] = ['a']; x // "a" y // undefined z // []

如果解構不成功,變數的值就等於 undefined 。

// 下面兩種情況都是解構不成功,foo 的值為 undefined
let [foo] = [];
let
[bar, foo] = [1];

不完全解構,即等號左邊的模式,只匹配一部分的等號右邊的陣列。這種情況下,解構依然可以成功。

let [x, y] = [1, 2, 3];
x // 1
y // 2

let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

如果等號的右邊不是陣列(或者嚴格地說,不是可遍歷的結構),那麼將會報錯。

// 報錯
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo]
= {};

預設值

解構賦值允許指定預設值。

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

注意,ES6 內部使用嚴格相等運算子(===),判斷一個位置是否有值。所以,只有當一個數組成員嚴格等於undefined,預設值才會生效。

let [x = 1] = [undefined];
x // 1

// null 不嚴格等於 undefined
let [x = 1] = [null];
x // null

如果預設值是一個表示式,那麼這個表示式是惰性求值的,即只有在用到的時候,才會求值。

function f() {
  console.log('aaa');
}

let [x = f()] = [1];

// 等價於
let x;
if ([1][0] === undefined) {
  x = f();
} else {
  x = [1][0];
}

預設值可以引用解構賦值的其他變數,但該變數必須已經宣告。

let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError: y is not defined