---
# System prepended metadata

title: '[JS]解構賦值'
tags: [' Javascript', ES6]

---

---
tags: ES6, Javascript
disqus: hackmd
---

# [JS]解構賦值

***IE 最新版瀏覽器 IE11 還不支援 Destructuring。***

[JavaScript ES6 Array and Object Destructuring Assignment 陣列和物件的解構賦值](https://www.fooish.com/javascript/ES6/array-and-object-destructuring.html)

解構賦值 (Destructuring Assignment)是一個在 ES6 的新特性，目的用於提取陣列或物件中的資料變成獨立變數。

物件解構賦值的基本使用方法如下：
```javascript=
let obj = {
  website: "pjchender",
  country: "Taiwan"
}

let {website, country} = obj;
console.log(website);  // pjchender
console.log(country);  // Taiwan
```

![](https://i.imgur.com/N0D7aSs.png)
圖片來源: [PJChender 部落格](https://pjchender.blogspot.com/2017/01/es6-object-destructuring.html)

所以真正被建立和賦值的 let{ } 當中，冒號（：）後的變數。
```javascript=
let obj = {
  website: "pjchender",
  country: "Taiwan"
}

let {website:wb, country:ct} = obj;

console.log(website, country);   //  Error:website in not defined
console.log(wb, ct)  // "pjchender", "Taiwan"
```

物件解構賦值的用途相當多（可參考[阮一峰-ECMAScript 6 入門](https://es6.ruanyifeng.com/#docs/destructuring)），其中在提取 JSON 數據時相當方便：
```javascript=
let data_JSON = {
  id: 74,
  website: "pjchender",
  country: "Taiwan",
  detail:{
    add: "Tainan",
    phone: "0933333333"
  }
}

let {id, website, country, detail} = data_JSON;
console.log(id, website, country, detail);
```