---
# System prepended metadata

title: 【js筆記】 解構賦值
tags: [JAVASCRIPT]

---

---
tags: JAVASCRIPT
---
【js筆記】 解構賦值
===
#### 原本方式
```javascript=
// #1 陣列解構
// 1. 請將 family 的值，一一賦予到變數上
// 2. 請將後面三個名字賦予到另一個陣列上
let family = ['小明', '杰倫', '阿姨', '老媽', '老爸'];
let ming = family[0];
let jay = family[1];
let auntie = family[2];
```
#### 解構賦值
```javascript=
let [ming, jay, , mom, dad] = family
console.log(ming, jay, mom, dad)
```
```javascript=
let { ming: Goku, family: [, mom] } = { ming: '小明', family: ['阿姨', '老媽', '老爸'] }
// 請問答案是什麼？
console.log(Goku, mom); 
// 小明，老媽
```

## 應用
1. 交換變數
```javascript=
let Goku = '悟空';
let Ginyu = '基紐';
[Goku, Ginyu] = [Ginyu, Goku]
console.log(Goku, Ginyu)
```

2. 取出一個值，並賦在新的變數名稱上
```javascript=
let GinyuTeam = {
  Ginyu: '基紐',
  Jeice: '吉斯',
  burter: '巴特',
  // ...
}
let { Ginyu: abc } = GinyuTeam;
let { Jeice } = GinyuTeam;
console.log(abc, Jeice)
```
3. 取出一個值，並賦在新的變數名稱上
```javascript=
let GinyuTeam = {
  Ginyu: '基紐',
  Jeice: '吉斯',
  burter: '巴特',
  // ...
}
let { Ginyu: abc } = GinyuTeam;
let { Jeice } = GinyuTeam;
console.log(abc, Jeice)
```
3. 預設值
```javascript=
let [ming = '小明', jay = '杰倫'] = ['阿明'] 
console.log(ming, jay)
// 阿明，杰倫
```
```javascript=
let { family: ming = '小明' } = {}
console.log(ming)
```

4. 物件內容複製，且避免參考 (淺複製)
```javascript=
// 將以下物件指向賦予到另一個物件上，並且避免參考
const GinyuTeam = {
  Ginyu: {
    name: '基紐'
  },
  Jeice: {
    name: '吉斯'
  },
  burter: { 
    name: '巴特'
  },
  // ...
}
const newTeam = {
  ...GinyuTeam
}
newTeam.ming = '小明'
console.log(newTeam, GinyuTeam)
```

> 深複製寫法
```javascript=
const newTeam2 = JSON.parse(JSON.stringify(GinyuTeam))
```