ES6中的解構(一)
阿新 • • 發佈:2019-01-13
傳統的賦值方式
let x = 1;
let y = 2;
let z = 3;
//或
let x = 1,
y = 2,
z = 3;
ES6中採用陣列模式 運算子
let [x,y,z] = [1,2,3];
let arr = [1,2,3];
let [a,b,c] = arr;
模式匹配,一一對應
let [a,,c] = [1,2,3]; //a = 1; c = 3;
let [a,b,c] = [1,2]; //c = undefined
帶預設值
let [a = 1] = ['a']; // a = 'a'; let [a = 1] = []; // a = 1;
需要特別注意,如果解構的值為undefined,則取預設值
let [b = 1] = [undefined]; //1
let [b = 1] = [null]; //null
解構的物件不僅僅可以是單一的值,也可以是物件或陣列
let [a,b,c] = [1,[2,3],4];
let [a,b,c] = [1,{x:'x'},4];
在物件的結構中,如下例,name是匹配模式,a才是變數
let {name:a,age:b} = {age:20,name:'abc'}; //a = 'abc';b = 20; let {name,age} = {age:20,name:'abc'}; //相當於let {name:name,age:age} = {age:20,name:'abc'} let {abc:name,age:age} = {age:20,name:'abc'}; //錯誤 name為變數, abc是物件中匹配的值