---
# System prepended metadata

title: JavaScript 觀念(ES6)
tags: [JavaScript]

---

# JavaScript 觀念(ES6)
###### tags: `JavaScript`

## JavaScript 常見縮寫

### 物件字面值 Object literals & Enhanced Object Literals

#### 1. 物件內的函式
```javascript=
const obj = {
    name: '物件',
    // fn: function(){
    //     return this.name;
    // 
    // 縮寫，Enhanced Object Literals
    fn() { 
        return this.name;
    }
    
}
console.log(obj.fn());//'物件'
```
#### 2. 物件內的變數
```javascript=
const name = '老王'
function fn() {
    return this.name;
}

const person = {
    //name: '老王'
    name,//縮寫
    fn
};
console.log(person);
console.log(person.fn());
```
---

### 展開 Spread syntax (...)
#### 1. 不同陣列合併
```javascript=
const groupA = ['A','B','C'];
const groupB = ['D','E'];
//const groupC = groupA.concat(groupB);
const groupC = [...groupA , ...groupB]
console.log(groupC)// ['A', 'B', 'C', 'D', 'E']

```
#### 2. 物件擴展
```javascript=
const methods = {
    fn1() {
        console.log(1);
    },
    fn2() {
        console.log(2);
    }
};
const newMethods = {
    ...methods,
    fn3() {
        console.log(3);
    }
    
};
console.log(newMethods);

```
---

### 參數預設值
```javascript=
function sum(a, b = 1) { //加入預設值來避免錯誤
    return a + b;
}
console.log(sum(1));
```
---

## 解構
1. 取出特定值作為變數
```javascript=
const person = {
    name: '老王',
    age: 25,
    like: "泡麵"
};

const { name, age } = person;
console.log(name, age);// 老王 25

```
2. 陣列解構
```javascript=
const array = ['A','B','C'];//陣列沒有名稱，只有索引位置
const [c, b, a] = array;// 照索引順序解構

console.log(c, b, a);// A B C
```
3. 解構加展開
```javascript=
const people = {
    A: {
        name: 'a',
        age: 10,
        like: 'apple'
    },
    B: {
        name: 'b',
        age: 15,
        like: 'banana'
    },
    C: {
        name: 'c',
        age: 20,
        like: 'cake'
    }
}

const { A, ...other } = people;
console.log(A, other);
//{name: 'a', age: 10, like: 'apple'} {B: {…}, C: {…}}
```
4. 解構加上重新命名
```javascript=
const people = {
    A: {
        name: 'a',
        age: 10,
        like: 'apple'
    }
}
let A = {};
const { A: a } = people;
console.log(a);
```
5. 函式的參數解構
```javascript=
const people = {
        name: 'a',
        age: 10,
        like: 'apple'
}
function callName({ name, age }) {
    console.log(name, age);
}
callName(people);// a 10
```
---
## 箭頭函式
箭頭函式改寫
```javascript=
// function fn(a, b) {
//     return a * b;
// }

// const fn = (a, b) => {
//     return a * b;
// }

//單行情況可以再更簡寫
const fn = (a, b) => a * b;

console.log(fn(2, 4));
```

```javascript=
//當參數只有一個時，可以省略()
const fn = n => n;
console.log(fn(2));
```

```javascript=
//當回傳一個物件時，要補上小括號
const fn = () => ({
    name: "老王"
});
console.log(fn());
```
