1. 程式人生 > 其它 >解構賦值1-陣列解構

解構賦值1-陣列解構

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

 

陣列的解構賦值的基本用法:

1.按照對應位置,對變數賦值

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

2.本質上,這種寫法屬於“模式匹配”,只要等號兩邊的模式相同,左邊的變數就會被賦予對應的值

 1 let [foo, [[bar], baz]] = [1, [[2], 3]];
 2 foo // 1
 3 bar // 2
 4 baz // 3
 5 let [ , , third] = ["foo", "bar", "baz"];
 6 third // "baz"
 7
let [x, , y] = [1, 2, 3]; 8 x // 1 9 y // 3 10 let [head, ...tail] = [1, 2, 3, 4]; 11 head // 1 12 tail // [2, 3, 4] 13 let [x, y, ...z] = ['a']; 14 x // "a" 15 y // undefined 16 z // []

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

 

3.不完全解構

等號左邊與一部分右邊匹配

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

 

4.如果等號右邊不是陣列或者不是可遍歷的結構,將會報錯

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

 

5.預設值

解構賦值允許指定預設值

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
let [x = 1] = [null];
x // null

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

 

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

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