在ES6中按照一定模式星虹,從數(shù)組和對象中提取值對變量進(jìn)行賦值,這被稱為解構(gòu)(Destructuring)
-
以前瘾婿,為變量賦值潮改,只能直接指定值
let a = 'a'; let b = 'b'; let c = 'c';
-
ES6 允許寫成下面這樣
let [a, b, c] = ['a', 'b', 'c'] console.log(a); //a console.log(c); //c
這表示,可以從數(shù)組中提取值罪既,按照對應(yīng)位置铸题,對變量賦值
舉幾個(gè)??
let [a,[[b],c]] = [1,[[2],3]] console.log(a); //1 console.log(b); //2 console.log(c); //3
let [, , thrid] = ['first', 'second', 'thrid'] console.log(thrid);//thrid
let [a, , c] = [1, 2, 3]; console.log(a); //1 console.log(c); //3
let [a, ...b] = [1, 2, 3, 4] console.log(a); // 1 console.log(b); // [2,3,4]
const [a, b, ...c] = ['a']; console.log(a); // a console.log(b); // undefined console.log(c); // []
如果解構(gòu)不成功,變量值就是undefined
let [a] = [];
let [b, c] = [1];
console.log(a); // undefined
console.log(b); // 1
console.log(c); // undefined
或者是不完全解構(gòu)琢感,就是等號左邊的模式丢间,只匹配一部分等號右邊的數(shù)組,這種情況是可以解構(gòu)成功
let [x, y] = [1, 2, 3];
console.log(x); //1
console.log(y); //2
let [a, [b], d] = [1, [2, 3], 4]
console.log(a); //1
console.log(b); //2
console.log(d); //4
如果等號右邊不是可以遍歷的解構(gòu)(不具有Iterator接口)驹针,就會報(bào)錯(cuò)
//以下全部報(bào)錯(cuò)
let [a] = 1;
let [a] = false;
let [a] = NaN;
let [a] = undefined;
let [a] = null;
let [a] = {};
Set結(jié)構(gòu)烘挫,也可以使用數(shù)組的解構(gòu)賦值
let [a, b, c] = new Set(['a', 'b', 'c'])
console.log(b); // b
事實(shí)上,只要數(shù)據(jù)結(jié)構(gòu)具有Iterator接口柬甥,都可以采用數(shù)組形式進(jìn)行結(jié)構(gòu)賦值.
//fibs是一個(gè)Generator函數(shù)饮六,原生具有Iterator接口
function* fibs() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b]
}
}
let [first, second, thrid, fourth, fifth, sixth] = fibs();
console.log(first); // 0
console.log(sixth); // 5