JavaScript自ES6之後便支援陣列和物件的解構(Destructuring)，使我們可以快速地將陣列的元素值和物件中的屬性值指派給變數或是常數來儲存。

```const array = [1, "2"];
const object = {
f1: 3,
f2: "4",
};

const [a, b] = array;
const { f1: c, f2: d } = object;

console.log(a);
console.log(b);
console.log(c);
console.log(d);```

1
2
3
4

```const array = [1, "2"];
const object = {
f1: 3,
f2: "4",
};

const a = array[0];
const b = array[1];
const c = object.f1;
const d = object.f2;

console.log(a);
console.log(b);
console.log(c);
console.log(d);```

```let { f1: c, f2: d } = {
f1: 1,
f2: "2",
};```

```let { f1, f2 } = {
f1: 1,
f2: "2",
};```

```const { f1 } = {
f1: 1,
f2: "2",
};```

```const o: {f1: number} = {
f1: 1,
f2: "2",
};```

```const o = {
f1: 1,
f2: "2",
};

const { f1 } = o;```

`const a: [number] = [1, "2"];`

`const [n] = [1, "2"];`

### 巢狀解構

```const o = {
f1: 3,
f2: "4",
f3: { f4: true },
};

const { f3: { f4 } } = o;

console.log(f4);```

### 參數解構

```const o = {
f1: 3,
f2: "4",
f3: { f4: true },
};

const isF4True = ({ f3: { f4 } }: { f3: { f4: boolean } }) => {
return f4;
};

console.log(isF4True(o));```

### 剩餘屬性解構

```const [n, s, ...remains] = [1, "2", true, Symbol(10)];

console.log(n);
console.log(s);
console.log(remains);```

1
2
[ true, Symbol(10) ]
```const o = {
f1: 3,
f2: "4",
f3: {
a: 6,
b: 7,
c: 8,
},
f4: { f5: true },
};

const { f3: { b, ...remains2 }, ...remains } = o;

console.log(b);
console.log(remains);
console.log(remains2);```

```7
{ f1: 3, f2: '4', f4: { f5: true } }
{ a: 6, d: 7 }```

```const o = {
f1: 3,
f2: '4',
f3: false,
};

const {f1: n, f2: ...remains} = o;```

### 陣列的直接解構

```let n, s;

[n, s] = [1, "2", false];

console.log(n);
console.log(s);```

1
2

### 解構時的預設值

```const o: { name: string, age: number, toString: () => string, "student-number"?: string} = {
name: "David",
age: 18,
toString: () => `\${o.age}: \${o.name}`,
};

const { "student-number": studentNumber = "unknown" } = o;

console.log(studentNumber);```

unknown

`const [n, s, o = {}] = [1, "2"];`