> ## Content Index
> Fetch the complete content index at: https://alvis.org.cn/llms.txt
> Use this file to discover other available public pages before exploring further.

# 🚞 前端展开运算符(...)应用场景
- URL: https://alvis.org.cn/35a166f0/
- Published: 2024-09-28T02:13:42.000Z
- Updated: 2026-11-30T07:48:10.000Z
- Description: 展开运算符基本用法以及使用场景
- Author: jie.chen
- Tags: 古法编程, 解决方案, JavaScript

> **前言 📝**  
>  
> 今天看到一个好玩的事情，就是如何在给后端传递参数的时候去掉多余的参数。然后就研究了一下，想到一个很好的解决方案，感觉代码很优雅。在这里分享一下。

## 1\. 优雅的传递参数

### 1.1 之前的写法

在之前，不管三七二十一，直接将所有的参数全部传递给后端，反正后端用不到的参数他不会在实体类中接收。要不就是用下面的这种写法：

```js
const queryParams = {
	pageNumber: 1,
	pageSize: 10,
	// 多余的参数，不需要传递给后端
	total: 100
}

async function fetchList() {
	const params = {
		pageNumber: queryParams.pageNumber,
		pageSize: queryParams.pageSize,
	}
	await fetch('http://xxxx/api/list', params)
}

```

可以看到，上面的代码非常的丑陋。

### 1.2 优雅的写法

```js
const queryParams = {
	pageNumber: 1,
	pageSize: 10,
	// 多余的参数，不需要传递给后端
	total: 100
}

async function fetchList() {
	const { total, ...params } = queryParams
	await fetch('http://xxxx/api/list', params)
}

```

我们可以通过结构+展开运算符来让代码变得优雅。

## 2\. 展开运算符其他应用场景

### 2.1 合并数组对象

```js
const arr1 = [1,2,3,4]
const arr2 = [5,6,7]

// 如果要是结构单个数组，就相当于对那个数组进行了浅拷贝
console.log([...arr1, ...arr2])

```

```js
const obj1 = { a: 1, b: 2 }
const obj2 = { a: 3, d: 2 }

// 如果要是结构单个对象，就相当于对那个对象进行浅拷贝
console.log({ ...obj1, ...obj2 })

```

### 2.2 在函数中使用

```js
function sum(...args) {
	return args.reduce((prev, item) => prev + item, 0)
}

console.log(1,2,3,4,5). // 15

```