1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| 在ES6之前: 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
let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4]
let [x, y, ...z] = ['a']; x // "a" y // undefined z // []
Destructuration 失敗example: let [foo] = []; let [bar, foo] = [1]; Output:foo : undefined
不完全Destructuration example: let [x, y] = [1, 2, 3]; x // 1 y // 2
let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4
若=左邊是array,但=右邊不是array,則會error //error let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};
Set也可以使用array Destructuration: let [x, y, z] = new Set(['a', 'b', 'c']); x // "a"
|