对象解构
- 对象解构的语法:在赋值操作符(=)左边放置一个对象字面量
let node = {
type:'Indet',
name:'noo'
}
let { type, name} = node;
console.log(type);
console.log(name);
- 对象的解构赋值:由于代码块语句不允许出现在赋值语句左侧,所以必须添加小括号将其转换为一个表达式。
let node = {
type:'Indet',
name:'noo'
},
type = 'Literal',
name = 'sss';
({ type, name } = node);
console.log(type); //'Indet'
console.log(name); //'noo'
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'
- 解构赋值表达式可以设置默认值:在属性名称后面添加一个等号和相应的默认值即可。
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
数组解构
- 数组解构语法:使用数组字面量,解构操作全部在数组内完成
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);
网友评论