10.扩展运算符

 

扩展运算符

扩展运算符(spread)也是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列,对数组进行解包

1.展开数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const fruits = ["apple", "banana", "grapes"];
console.log(fruits);
// (3) ['apple', 'banana', 'grapes']
console.log(...fruits);
// apple banana grapes

function test1(p1, p2) {
console.log(arguments);
// Arguments(3) ['apple', 'banana', 'grapes', callee: ƒ, Symbol(Symbol.iterator): ƒ]
console.log(p1);
// apple
console.log(p2);
// banana
}
test1(...fruits);
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
1.数组的合并
const fruits = ["apple", "banana"];
const lang = ["Java", "Go"];
const combine1 = fruits.concat(lang);
console.log(combine1);
// Array(4)
const combine2 = [...fruits, ...lang];
console.log(combine2);
// Array(4)

// 2.数组的克隆
const letter = ["A", "B", "C"];
const copy = [...letter];
console.log(copy);
// (3) ['A', 'B', 'C']

// 3.将伪数组转为真正的数组
const divs = document.querySelectorAll("div");
const divArray = [...divs];
console.log(divs);
// NodeList(3) [div, div, div]
console.log(divArray);
// (3) [div, div, div]

</script>
</body>
</html>

2.展开对象

1
2
3
4
5
6
7
8
9
10
11
12
13
const info = {
id: 1,
name: "xiaoming",
age: 10
};
const score = {
math: 90,
physics: 80,
music: 95
};
const stuObj = {...info, ...score};
console.log(stuObj);
// {id: 1, name: 'xiaoming', age: 10, math: 90, physics: 80, …}