解構(gòu)賦值
解構(gòu)賦值語法是一種javascript表達(dá)式。可以將數(shù)組的值或者對(duì)象屬性取出,賦值給其他變量。
首先解構(gòu)賦值在項(xiàng)目中越來越常使用的一種賦值,常見的有數(shù)組和對(duì)象中獲取來賦值。
數(shù)組解構(gòu):
let [a,b] = [1,2];
//a:1
//b:2
let [a,...b] = [1,2,3,4]
//a:1
//b:[2,3,4] 由于是...擴(kuò)展運(yùn)算,跟數(shù)組合并的[...a,...b]相同,所以剩余屬性都是b的
let arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];
// arr:[1, 3, 2] //這個(gè)為交換變量
//當(dāng)沒有這么多值后,其賦值為undefined
const foo = ['one', 'two'];
const [red, yellow, green, blue] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // undefined
console.log(blue); //undefined
對(duì)象解構(gòu):
let {a,b} = {a:1,b:2}
//a:1
//b:2
let [a = 1] = [];
let {b = 2} = {b: undefined}
let {c = 3} = {c: null}
let {d = 4} = {d: 5}
//a:1
//b:2
//c:3
//d:5
//首先不難理解,a=1為默認(rèn)賦值,當(dāng)其解構(gòu)賦值數(shù)組為空時(shí),或者對(duì)象為undefined、null時(shí),則就會(huì)使用其默認(rèn)值
let {a,...b} = {a: 1, b: 2, c: 3}
//a:1
//b:{b: 2, c: 3} 由于是...擴(kuò)展運(yùn)算,跟對(duì)象合并的{...a,...b}相同,所以剩余屬性都是b的
const obj = {
self: '123',
__proto__: {
prot: '456',
},
};
const { self, prot } = obj;
// self "123"
// prot "456" (Access to the prototype chain) 還有就是獲取屬性的
其余的一些比較復(fù)雜,可以去官網(wǎng)參考,所以就一一復(fù)述了。
學(xué)會(huì)這些基本夠用了。

浙公網(wǎng)安備 33010602011771號(hào)