解構(gòu)賦值:按照一個(gè)數(shù)據(jù)值的結(jié)構(gòu)净赴,快速解析獲取到其中的內(nèi)容
-
數(shù)組解構(gòu)賦值
1.想要幾個(gè)就幾個(gè)
2.設(shè)置默認(rèn)值也行(默認(rèn)解構(gòu))let ary = [12, 23, 34, 45, 56]; let [a, b, c] = ary; console.log(a, b, c); // 12 23 34 let [d] = ary; console.log(d); // 12 // 省略賦值 let [e, , f] = ary; console.log(e,f); // 12 34
3.不僅可以解構(gòu)成單個(gè)值犹撒,還可以返回個(gè)數(shù)組let ary = [12]; let [a, b = 0] = ary; console.log(a, b); // 12 0
4.互換位置更加方便let ary = [12, 23, 34, 45, 56]; let [a, ...b] = ary; console.log(a, b); // 12 [23,34,45,56] let [a, ...b, c] = ary; // SyntaxError: Rest element must be last element
let a = 12, b = 13; [a, b] = [b, a]; console.log(a, b); // 13 12
-
對(duì)象解構(gòu)賦值
1.對(duì)象解構(gòu)賦值默認(rèn)情況下要求:左側(cè)變量名和對(duì)象中的屬性名一致才可以
2.給不存在的屬性設(shè)置默認(rèn)值let obj = {name: 'xxx', age: 25, sex: 0}; let {name, age} = obj; console.log(name, age); // "xxx" 25
3.給解構(gòu)的屬性名起別名作為需要使用的變量let obj = {name: 'xxx', age: 25, sex: 0}; let {friend = 0} = obj; console.log(friend); // 0
let obj = {name: 'xxx', age: 25, sex: 0}; let {age: ageAA} = obj; console.log(age); // Uncaught ReferenceError: age is not defined console.log(ageAA); // 25