數組和對象的解構賦值是ES6中新增的一種語法,可以快速、方便地從數組或對象中提取出需要的元素,然后賦值給變量。
數組解構賦值
數組解構賦值的語法格式為:
let [變量1, 變量2, ..., 變量n] = 數組;
其中,方括號表示數組,等號左邊的方括號表示解構賦值的語法,等號右邊的數組是要被解構的數組,變量1到變量n是要接收數組中的元素的變量名。
舉個例子:
let arr = [1, 2, 3];
let [a, b, c] = arr;
console.log(a); // 輸出1
console.log(b); // 輸出2
console.log(c); // 輸出3
對象解構賦值
對象解構賦值的語法格式為:
let {屬性1: 變量1, 屬性2: 變量2, ..., 屬性n: 變量n} = 對象;
其中,花括號表示對象,等號左邊的花括號表示解構賦值的語法,等號右邊的對象是要被解構的對象,屬性1到屬性n是要接收對象中的屬性名,變量1到變量n是要接收對象中屬性的值的變量名。
舉個例子:
let obj = {a: 1, b: 2, c: 3};
let {a, b, c} = obj;
console.log(a); // 輸出1
console.log(b); // 輸出2
console.log(c); // 輸出3
解構賦值還可以設置默認值,當要解構的對象或數組中沒有該屬性或元素時,就會使用默認值。
舉個例子:
let obj = {a: 1, b: 2};
let {a = 0, b = 0, c = 0} = obj;
console.log(a); // 輸出1
console.log(b); // 輸出2
console.log(c); // 輸出0
在解構賦值中,可以通過使用...運算符來獲取數組或對象中剩余的元素,生成一個新的數組或對象。
舉個例子:
let arr = [1, 2, 3, 4];
let [a, b, ...rest] = arr;
console.log(a); // 輸出1
console.log(b); // 輸出2
console.log(rest); // 輸出[3, 4]
let obj = {a: 1, b: 2, c: 3, d: 4};
let {a, b, ...rest} = obj;
console.log(a); // 輸出1
console.log(b); // 輸出2
console.log(rest); // 輸出{c: 3, d: 4}