DAY 11
0
Modern Web

## [Day11] ES2015(ES6)＆ES2018(ES9) - 剩餘/展開運算子(Rest/Spread Operator)

• 剩餘(Rest): 跟展開的概念有點相反，集合不確定個數或剩餘的元素，並回傳為陣列或物件。常使用在 參數傳遞 上。

## 展開運算子

### 字串

``````const str = "One Punch Man";
const arr = [...str];
// ["O", "n", "e", " ", "P", "u", "n", "c", "h", " ", "M", "a", "n"]
``````

### 陣列

``````const arr1 = ["a", "b", "c"];
const arr2 = ["e", "f", ...arr1]; // ['e', 'f', 'a', 'b', 'c']
const arr1_1 = [...arr1]; // ["a", "b", "c"] 將 arr1 clone 到 arr1_1
``````

``````const sumFunc = (a, b, c) => a + b + c;
const arr = [1, 2, 3];
const result = sumFunc(...arr1); // 6
``````

### 物件

``````const obj1 = { name: "One Punch Man", age: 28 };
const obj1_1 = { ...obj1 };
// {name: "One Punch Man", age: 28}  將 obj1 clone 到 obj1_1
``````

## 剩餘運算子

### 函數參數

``````const sumFunc = (...args) => {
let result = 0;
args.forEach((n) => (result += n));
return result;
};
const result1 = sumFunc(2); // 2
const result2 = sumFunc(3, 53, 5, 64); // 125
``````

### 物件屬性

``````const obj = { name: "One Punch Man", age: 28, lead: "Saitama", gender: "male" };
const { name, lead, ...oherProps } = obj;
console.log(otherProps); // Uncaught ReferenceError: otherProps is not defined
``````
``````const { name, lead, ...oherProps } = {
name: "One Punch Man",
age: 28,
gender: "male",
};
console.log(otherProps); // { age: 28, gender: "male" }
``````

## 小結

• 以剩餘運算子`...`代替函式的隱藏屬性 `arguments`
• `...`在寫法上要緊鄰後面的對象
• 以展開運算子取代 `slice``concat` 跟陣列處理有關的寫法
• 以展開運算子取代 `Object.assign` 等有關物件的淺拷貝寫法
• 以展開運算子取代 `fn.apply(this, [args])` 等作為不確定參數個數的傳遞方式