# 8.3 Spread and Rest Operator

Spread Operator(展開運算子)、Rest Operator(其餘運算子)。這兩個運算子，符號都是一樣的，即 **`...`**。

## Spread 運算子(...)

以陣列為例：

```javascript
var a = [1, 2, 3];
var b = [4, ...a, 5];
console.log(a); // [1, 2, 3]
console.log(b); // [4, 1, 2, 3, 5]
```

以物件為例：

```javascript
var c = {
  a: 1,
  b: 2
};
var d = {
  b: 3,
  ...c,
  f: 6
};

console.log(c); // {a: 1, b: 2}
console.log(d); // {a: 1, b: 2, f: 6}
```

改成以下：

```javascript
var c = {
  a: 1,
  b: 2
};
var d = {
  ...c,
  b: 3,
  f: 6
};

console.log(c); // {a: 1, b: 2}
console.log(d); // {a: 1, b: 3, f: 6}
```

範例：

{% embed url="<https://codepen.io/carlos411/pen/zYZqMrx>" %}

## Rest 運算子(...)

參數傳遞至函式中時，不確定傳過來的參數有幾個，那就用 **`...`** 這語法，再加上一個自訂的變數名稱，例如範例1的 **`...others`**：此時在函式中，就可以使用 others 這個陣列來取得參數：

範例 1：

```javascript
function add(...others){
  console.log(others); // [1, 2, 3, 4, 5]
  let total = 0;
  for(let i = 0; i < others.length; i++){
    total += others[i];
  }
  return total;
}

let result = add(1, 2, 3, 4, 5);
console.log(result); // 15
```

{% embed url="<https://codepen.io/carlos411/pen/jOBrbLJ>" %}

範例 2：

延續上例，測試看看這個：

```javascript
/* Rest Operator：用在函式 */
function add(a, b, ...others){
  console.log(a); // 1
  console.log(b); // 2
  console.log(others); // [3, 4, 5]
  let total = 0;
  for(let i = 0; i < others.length; i++){
    total += others[i];
  }
  return total;
}

let result = add(1, 2, 3, 4, 5);
console.log(result); // 12
```

{% hint style="success" %}
Rest Operator 參數一定要放在最後。
{% endhint %}

{% embed url="<https://codepen.io/carlos411/pen/PojZGBM>" %}
