ES6中的解構:按照一定模式,從數組和對象中提取值,對變量進行賦值
數組的元素按照次序排列,變量取值按照位置決定;對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
1.數組的結構賦值
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined 如果解構不成功,則等於 undefined
z // []
-----------------------------------------------------
不完全解構
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
----------------------------------------------------
等號右邊不是數組則報錯
let[foo] = 1; //報錯
let[foo] = false; //報錯
---------------------------------------------------
對於Set結構,可以使用數組的解構賦值
let [foo = true] = [];
foo // true
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
--------------------------------------------------
默認值
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
只有當一個數組成員嚴格等於 undefined ,默認值纔會生效。
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
默認值可以引用解構賦值的其他變量,但是該變量必須已經聲明。
let[x = 1,y = x] = []; //x = 1, y = 1
let[x = 1,y = x] = [2]; //x = 2, y = 2
let[x = 1,y = x] = [2,3]; //x = 2,y = 3
let[y = x,x = 1] = []; //報錯,y還沒有聲明
2.對象的解構賦值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
沒有對應的同名屬性,則返回 undefined
let {foo} = {bar: 'baz'};
foo // undefined