對象解構(gòu)
- 對象解構(gòu)的語法:在賦值操作符(=)左邊放置一個(gè)對象字面量
let node = {
type:'Indet',
name:'noo'
}
let { type, name} = node;
console.log(type);
console.log(name);
- 對象的解構(gòu)賦值:由于代碼塊語句不允許出現(xiàn)在賦值語句左側(cè)佛析,所以必須添加小括號將其轉(zhuǎn)換為一個(gè)表達(dá)式。
let node = {
type:'Indet',
name:'noo'
},
type = 'Literal',
name = 'sss';
({ type, name } = node);
console.log(type); //'Indet'
console.log(name); //'noo'
- 函數(shù)中也可以傳入解構(gòu)表達(dá)式
let node = {
type:'Indet',
name:'noo'
},
type = 'Literal',
name = 'sss';
function outPut(value) {
console.log(value === node);
}
outPut({ type, name } = node);
console.log(type); //'Indet'
console.log(name); //'noo'
- 解構(gòu)賦值表達(dá)式可以設(shè)置默認(rèn)值:在屬性名稱后面添加一個(gè)等號和相應(yīng)的默認(rèn)值即可京景。
let node = {
type:'Indet',
name:'noo'
};
let { type, name, value = true} = node;
console.log(type); //'Indet'
console.log(name); //'noo'
console.log(value); //true
let node = {
type:'Indet',
name:'noo'
};
// type:localType語法的含義是讀取名為type的屬性并將其值存儲在變量localType中
let { type:localType, name:localName} = node;
console.log(localType); //'Indet'
console.log(localName); //'noo'
let node = {
type:'Identifier',
name:'noo',
loc: {
start: {
line: 1,
column:1
},
end: {
line: 1,
column: 4
}
}
}
let { loc: {start }} = node;
console.log(start.line); //1
console.log(start.column); //1
數(shù)組解構(gòu)
- 數(shù)組解構(gòu)語法:使用數(shù)組字面量鸭廷,解構(gòu)操作全部在數(shù)組內(nèi)完成
let colors = ['red', 'grren', 'blue'];
let [first, second] = colors;
console.log(first); //'red'
console.log(second); //'grren'
let colors = ['red', 'grren', 'blue'],
first = '111',
second = '222';
[first,second] = colors;
console.log(first);
console.log(second);