对象解构
- 对象字面量的语法形式是在一个赋值操作符左边放置一个对象字面量
1
2
3
4
5
6
7let node = {
type: "Identifier",
name: "foo"
}
let { type, name } = node
console.log(type) // "Identifier"
console.log(name) // "foo" - 如果已经存在type、name,重新赋值 使用解构的话则需要在表达式两侧加小括号
1
2
3
4
5
6
7
8let node = {
type: 'Identifier',
name: 'angela'
},
type = 'demo',
name = 1;
//添加小括号可以将块语句转化为一个表达式,从而实现整个解构赋值的过程
({ type, name } = node) - 如果指定的局部变量名称在对象中不存在,那么这个局部变量会被赋值为
undefined
,也可以自己设置一个默认值1
2
3
4
5
6
7
8let node = {
type: "Identifier",
name: "foo"
};
let { type, name, value = true } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // true - 嵌套对象解构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17let node = {
type: "Identifier",
name: "foo",
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数组解构
先来看几个简单明了的例子1
2
3let colors = ['red', 'green', 'blue']
let [, , thirdColor] = colors
console.log(thirdColor) // blue1
2
3
4
5let colors = ['red', 'green', 'blue'],
firstColor = 'black',
secondColor = 'purple';
[firstColor, secondColor] = colors
console.log(firstColor, secondColor) // red green - 变量交换
1
2
3
4
5
6
7
8
9// 传统做法
let a = 1,
b = 2,
tmp;
tmp = a;
a = b;
b = tmp;
console.log(a); // 2
console.log(b); // 11
2
3
4
5// 使用解构赋值
let a = 1,
b = 2;
[a, b] = [b, a]
console.log(a, b) // 2 1 - 数组解构中有一个不定元素的概念,可以通过…语法将数组中的其余元素赋值给一个特定的变量
1
2let colors = ['red', 'green', 'blue'];
let [firstColor, ...restColors] = colors//restColors包含两个元素green和blue - 最好的办法是既使用默认值,又使用解构
1
2
3
4
5
6
7
8const DEFAULT_REQUEST_OPTIONS = {
url: '',
data: {},
header: {'Content-Type': 'application/json'},
method: 'GET',
dataType: 'json'
}
let {url, data, header, method, dataType, mock=false} = options