解構賦值
數組的解構賦值
function fn() {
return 7;
}
let [a, [[b, ...d], c, e = 6, f = a, g = fn()]] = [1, [[2, 3], 4]];
console.log(a); // 1 不解釋
console.log(b); // 2 不解釋
console.log(c); // 4 不解釋
console.log(d); // [3] 展開符將剩余的所有元素當做一個數組返回
console.log(e); // 6 如果e === undefined e等于默認值
console.log(f); // 1 a必須被定義如果a未被定義則報錯
console.log(g); // 7 惰性求職,當給g變量賦值時才會執行fn方法
對象的解構賦值
let {a,c} = {a:1,c:2};
//以上表達式其實是以下表達式的簡寫
let {a:a,c:c} = {a:1,c:2};
//以下表達式中的a,c是模式;b,d才是變量
let {a:b,c:d} = {a:1,c:2};
console.logc(b);//1
console.logc(d);//2
console.logc(a);//a is undefined
console.logc(c);//c is undefined
function fn() {
return 7;
};
let obj = {};
let arr = [];
let cc, dd, ee;
({a: obj.prop, b: arr[0], cc=3, dd=obj.prop, e: ee = fn()} = {a: 1, b: 2, e: 3});
console.log(obj); //{prop:1}
console.log(arr); //[2]
console.log(cc); //3
console.log(dd); //1 dd===undefined 使用obj.prop為默認值
console.log(ee); //3 e!=undefined 使用e給ee賦值,e===undefined使用惰性求職給ee設置默認值