在ES6中,使用 ... 来表示展开运算符,它可以将数组/对象进行展开。

通过一个简单的例子来了解一下展开运算符的作用。

code.ts
1
// 首先声明一个数组
2
const arr1 = [1, 2, 3];
3
4
// 其次声明另一个数组,我们期望新数组中包含数组arr1的所有元素,那么可以利用暂开运算符
5
const arr2 = [...arr1, 4, 5, 6];
6
7
// 那么arr2就变成了 [1, 2, 3, 4, 5, 6]

当然,展开对象也可以得到类似的结果。

code.ts
1
const object1 = {
2
a: 1,
3
b: 2,
4
c: 3
5
}
6
7
const object2 = {
8
...object1,
9
d: 4,
10
e: 5,
11
f: 6
12
}
13
14
// object2的结果等价于
15
object2 = {
16
a: 1,
17
b: 2,
18
c: 3,
19
d: 4,
20
e: 5,
21
f: 6
22
}

在解析结构中,我们也常常使用展开运算符。

code.ts
1
const tom = {
2
name: 'TOM',
3
age: 20,
4
gender: 1,
5
job: 'student'
6
}
7
8
const { name, ...others } = tom;
9
10
// others = {age: 20, gender: 1, job: "student"}

利用这样的方式,我们可以将 tom 对象中的剩余参数全部丢在 others 中,而不用一个一个的去列举所有的属性。

在 react 组件中,我们也常常使用展开运算符来传递数据。

code.ts
1
const props = {
2
size: 1,
3
src: 'xxxx',
4
mode: 'si'
5
}
6
7
const { size, ...others } = props;
8
9
// 利用展开运算符传递数据
10
<button {...others} size={size} />

展开运算符还可以运用在函数参数中,放置于函数参数的最后一个参数(且只能放置于最后),表示不定参。

code.ts
1
// 求所有参数之和
2
const add = (a, b, ...more) => {
3
return more.reduce((m, n) => m + n) + a + b
4
}
5
6
console.log(add(1, 23, 1, 2, 3, 4, 5)) // 39

展开运算符能够大大提高我们的代码效率,因此记住这些常见的应用场景非常重要。

专栏首页
到顶
专栏目录