ES6 允許按照一定模式财搁,從數(shù)組和對象中提取值,對變量進行賦值鲫尊,這被稱為解構
ES5
let a = 1;
let b = 2;
let c = 3;
ES6
let [a, b, c] = [1, 2, 3];
等號兩邊的模式相同渴庆,左邊的變量就會被賦予對應的值
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
z // []
如果解構不成功称鳞,變量的值就等于undefined苍糠。
另一種情況是不完全解構叁丧,即等號左邊的模式,只匹配一部分的等號右邊的數(shù)組岳瞭。這種情況下拥娄,解構依然可以成功。
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
默認值
解構賦值允許指定默認值寝优。
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
ES6 內部使用嚴格相等運算符(===)条舔,判斷一個位置是否有值枫耳。所以乏矾,如果一個數(shù)組成員不嚴格等于undefined,默認值是不會生效的
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
如果默認值是一個表達式迁杨,那么這個表達式是惰性求值的钻心,即只有在用到的時候,才會求值铅协。
function f() {
console.log('aaa');
}
let [x = f()] = [1];
等價
let x;
if ([1][0] === undefined) {
x = f();
} else {
x = [1][0];
}
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError
最后一個表達式之所以會報錯捷沸,是因為x用到默認值y時,y還沒有聲明狐史。
對象的解構賦值
解構不僅可以用于數(shù)組痒给,還可以用于對象
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
對象的解構與數(shù)組有一個重要的不同。數(shù)組的元素是按次序排列的骏全,變量的取值由它的位置決定苍柏;而對象的屬性沒有次序,變量必須與屬性同名姜贡,才能取到正確的值
let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined
變量沒有對應的同名屬性试吁,導致取不到值,最后等于undefined楼咳。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
未完熄捍。烛恤。。余耽。