定義
ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構
數組的解構賦值
- 以前,為變量賦值,只能直接指定值。
let a = 1; let b = 2; let c = 3;
-
es6寫法
let [a, b, c] = [1, 2, 3];
-
不完全解構--解構不成功,值都會等於
undefinedlet [x, y, ...z] = ['a']; x // "a" y // undefined z // [] let [bar, foo] = [1]; foo //undefined let [foo] = []; foo //undefined
-
不完全解構的另外一種情況
//等號左邊的模式,只匹配一部分的等號右邊的數組 ,此時解構成功 let [x, y] = [1, 2, 3]; x // 1 y // 2 let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4 //等號的右邊不是數組(或者嚴格地說,不是可遍歷的結構,參見《Iterator》一章),那么將會報錯,以下寫法都會報錯 // 報錯 let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};
-
Set 結構,也可以使用數組的解構賦值。
let [x, y, z] = new Set(['a', 'b', 'c']); x // "a"
數組解構賦值允許默認值
- ES6 內部使用嚴格相等運算符(
===),判斷一個位置是否有值。所以,只有當一個數組成員嚴格等於undefined,默認值才會生效。//默認值生效了 let [foo = true] = []; foo // true let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b' let [x = 1] = [undefined]; //x=1 //默認值沒有生效 let [x = 1] = [null]; x // null
-
默認值是一個表達式,那么這個表達式是惰性求值的,即只有在用到的時候,才會求值
function f() { console.log('aaa'); } let [x = f()] = [1]; //x=1
-
默認值可以引用解構賦值的其他變量,但該變量必須已經聲明。
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
