解構賦值
- 按照必定模式,從數組和對象中提取值,對變量進行賦值,這被稱爲解構。
1.常看法構賦值
* let [a, b, c] = [1, 2, 3]; //a=1,b=2,c=3
* let [a, ...b] = [1, 2, 3, 4]; a // 1; b // [2, 3, 4]
* let [a] = []; //a=undefined
複製代碼
2.默認值
* let [x, y = 'b'] = ['a']; //x=a;y=b
* let [x = 1] = [undefined]; // x=undefined
* let [x = 1] = [null]; // x=null
複製代碼
注意,ES6 內部使用嚴格相等運算符(===),判斷一個位置是否有值。因此,只有當一個數組成員嚴格等於undefined,默認值纔會生效。
undefined===undefined //true;
undefined===null //false
複製代碼
3.對象的解構賦值
let { x, y } = { x: "a", y: "b" }; //x="a";y ="b"
let x; ({x} = {x: 1}); //x=1;對於已經聲明的變量,進行解構賦值,須要加‘()’,不然會報錯
複製代碼
let { x: y } = { x: 'a', y: 'b' };// y ="a"
複製代碼
上述狀況,對象的解構賦值的內部機制,是先找到同名屬性,而後再賦給對應的變量。真正被賦值的是後者,而不是前者。
4.字符串的解構賦值
let [a, b, c, d, e] = 'hello'; // a="h";b="e";c="l";d ="l";e="o";
複製代碼
5.數值和布爾值的解構賦值
若是等號右邊是數值和布爾值,進行解構賦值時會先轉爲對象。若是右邊是undefined和null則沒法轉爲對象,由於對它們進行解構賦值,都會報錯(TypeError)。
6.函數參數的解構賦值
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
複製代碼