> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/javascript-web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/javascript-web/8.-ecmascript/8.5-destructuring-assignment.md).

# 8.5 解構賦值

## 解構賦值(Destructuring Assignment)

例 1：

```javascript
var myarr = [1, 2, 3];

var [a, b] = myarr; // 宣告變數 a 和 b，值分別是 myarr 裡依序的資料

console.log(a); // 1
console.log(b); // 2
```

例 2：

```javascript
var myobj = {a: "test1", b: "test2"};

var {a, b} = myobj; // 宣告變數 a 和 b，值分別是 myobj 對應的 key

console.log(a); // test1
console.log(b); // test2
```

例 3：

```javascript
let a = 0;
let b = 1;

[a, b] = [b, a]; // 將原來 b 的值給變數 a；將原來 a 的值給變數 b
console.log(a);  // 1
console.log(b);  // 0
```

例 4(常用)：將陣列中，兩個項目對調：

```javascript
let arr = ["a", "b", "c", "d"];
[arr[1], arr[2]] = [arr[2], arr[1]];

console.log(arr); // ["a", "c", "b", "d"]
```
