扩展运算符
时间: 2023-07-04 13:06:12 浏览: 67
扩展运算符(spread operator)是在ES6中引入的种新特性,用三个点(...表示,可以将一个可迭代对象(如数组、字符串等)展开成多个元素,并且可以在函数调用的参数中使用。
1. 展开数组
可以使用扩展算符将数组展多个元素:
javascript
const arr1 = [1, , 3];
const arr2 = [...arr1 4, 5];
console.log(arr2); [1, 2, 3, 4, 5]
```
2. 合并数组
使用扩展运算符还可以方便地合并多个数组:
```javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5]
```
3. 复制数组
使用扩展运算符可以很方便地复制一个数组:
```javascript
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]
```
4. 字符串转数组
可以使用扩展运算符将字符串转换为字符数组:
```javascript
const str = "hello";
const arr = [...str];
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
```
5. 函数调用参数
使用扩展运算符可以方便地将数组作为函数的参数传递:
```javascript
function myFunction(x, y, z) {
console.log(x, y, z);
}
const arr = [1, 2, 3];
myFunction(...arr); // 1 2 3
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)