变量的解构赋值
/ / 点击 / 阅读耗时 2 分钟简介
- 基本用法:
let [a, b, c] = [1, 2, 3]
- 默认值:
let [ n = 1] = []
- 解构不成功,变量的值等于undefined
对象的解构赋值
- 基本用法:
let {foo, bar} = {foo: 'aaa', bar: 'bbb'}
- 默认值:
let {x = 3} = {x: undefined}
- 默认值生效的条件是对象的属性值严格等于undefined
字符串的解构赋值
- 基本用法:
cosnt [a, b, c, d, e] = 'hello'
//a = ‘h’, b = ‘e’
用途:
交换变量的值:
1
2
3let x = 1;
let y = 2;
[x, y ] = [y, x]从函数返回多个值:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();定义函数参数:
1
2
3
4
5
6
7// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});提取JSON数据:
1
2
3
4
5
6
7
8
9
10let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]遍历map结构:
1
2
3
4
5
6
7
8
9const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world