-
Notifications
You must be signed in to change notification settings - Fork 0
/
解构赋值.html
73 lines (60 loc) · 1.8 KB
/
解构赋值.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//数组的解构赋值
let [a, b, c] = [1, 2, 3];
//模式匹配
let [foo, [[bar], baz]] = [1, [[2], 3]];
//等式两边的模式相同即可解构,即使只有一部分模式相同。
//允许设置默认值
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
//对象的解构赋值
//字符串的解构赋值 --> 字符串转化为类似数组的对象
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
//用途
//1交换变量的值:
let x = 1;
let y = 2;
[x,y] = [y,x];
//2 函数返回多个值的接受
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
//3提取JSON数据 -->这个很有用
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number); // 42, "OK", [867, 5309]
//4 输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");
</script>
</body>
</html>