front-end-interview-handbook/packages/quiz/questions/can-you-give-an-example-for.../zh-CN.mdx

39 lines
687 B
Plaintext

---
title: 您能提供一个解构对象或数组的例子吗?
---
解构是一个在 ES2015 中可用的表达式,它使得能够以简洁和方便的方式提取对象或数组的值,并将它们置于不同的变量中。
## 数组的解构
```js
// 变量赋值
const foo = ['one', 'two', 'three'];
const [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
```
```js
// 交换变量
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
```
## 对象的解构
```js
// 变量赋值
const o = { p: 42, q: true };
const { p, q } = o;
console.log(p); // 42
console.log(q); // true
```