---
# System prepended metadata

title: 20220318 ES6/ES2015語法補充

---

# 20220318 ES6/ES2015語法補充

## ES6/ES2015語法補充

### arrow function省去return的shortcut

一般寫法
```javascript=
const plus = (a, b) => {
    return a + b;
  };

```

shorthand(箭頭涵式)
```javascript=
const plus = (a, b) => a + b;
```
---
### 如果物件的key跟value同名的時候，可以寫一個就好

一般寫法
```javascript=
 let name = "kk";
 let age = 18;

 const cat = {
    name: name,
    age: age,
 };
 console.log(cat);
```
shorthand
```javascript=
 let name = "kk";
 let age = 18;

 const cat = {
    name,
    age,
 };
```
---

## 物件解構

解構物件中的屬性

一般寫法
```javascript=
  const cat = {
    name: "kk",
    age: 18,
  };

  let name = cat.name;
  let age = cat.age;

  console.log(name, age);
```
shorthand
```javascript=
  const cat = {
    name: "kk",
    age: 18,
  };

  let { name, age } = cat;

  console.log(name, age);
```

如果變數名稱有重複時，可以解構後重新命名變數

```javascript=
  const cat = {
    name: "kk",
    age: 18,
  };

  let name = "tt";
  let { name: petname, age } = cat;

  console.log(petname, age);
```

### function 的解構方式

```javascript=
  const cat = {
    name: "kk",
    age: 18,
  };

  function hello(h) {
    const { name, age } = h;
    console.log(name, age);
  }
  hello(cat);
```

懂上面的手法後，這裡也可以直接將解構寫在參數中，重新命名變數也可以使用

```javascript=
  const cat = {
    name: "kk",
    age: 18,
  };

  function hello({ name: petname, age }) {
    console.log(petname, age);
  }
  hello(cat);
```

---

### 點點點(...)

1. 可當作展開 
設置接住展開陣列後的容器c，將a和b在c陣列中展開
(合併多數資料時concat只能一次做兩個，展開可以一次合併多個)
```javascript=
  const a = [1, 2, 3];
  const b = [4, 5, 6];

  const c = [...a, ...b];
  console.log(c);
```

2. spread operator

一般來說將陣列丟到參數，只會是獨立值
```javascript=
  const a = [1, 2, 3];
  const b = [4, 5, 6];

  function sayHello(x, y, z) {
    console.log(x, y, z);
  }

  sayHello(a);
```
![](https://i.imgur.com/Ga4Qj3A.png)

但如果將a在參數中展開的話，便會將a陣列的值展開後傳播出去，到function的參數，此手法為splat operator

```javascript=
  const a = [1, 2, 3];
  const b = [4, 5, 6];

  function sayHello(x, y, z) {
    console.log(x, y, z);
  }

  sayHello(...a);
```

![](https://i.imgur.com/385gcUr.png)

3. Rest parameters 收合多的參數

一般來說少給參數值會顯示undifined，多給的參數值並不會顯示，但如果今天想要接收多的參數值，可以將...加在後方
(...收合會將該值預設變陣列，展開不會)

```javascript=
  function sayHello(x, y, ...z) {
    console.log(x, y, z);
  }

  sayHello(1, 2, 3, 4, 5);
```
![](https://i.imgur.com/4AwCuvC.png)

搭配解構的方式

```javascript=
  const person = ["Amy", "John", "Mike", "Tim"];

  const [h1, ...h2] = person;
  console.log(h1, h2);
```
![](https://i.imgur.com/sqjLqR8.png)
