解構賦值:按照一個數據值的結構,快速解析獲取到其中的內容
-
數組解構賦值
1.想要幾個就幾個
2.設置默認值也行(默認解構)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.不僅可以解構成單個值,還可以返回個數組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
-
對象解構賦值
1.對象解構賦值默認情況下要求:左側變量名和對象中的屬性名一致才可以
2.給不存在的屬性設置默認值let obj = {name: 'xxx', age: 25, sex: 0}; let {name, age} = obj; console.log(name, age); // "xxx" 25
3.給解構的屬性名起別名作為需要使用的變量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