# 5 个 实用 JS 解构用法

## 1. 交换变量

``````let a = 1;
let b = 2;
let temp;

temp = a;
a = b;
b = temp;

a; // => 2
b; // => 1
``````

`temp`是一个临时变量，它先保存`a`的值。然后把`b`的值赋值给`a`，接着将`temp`值赋给 `b`

``````let a = 1;
let b = 2;

[a, b] = [b, a];

a; // => 2
b; // => 1

``````

`[a，b] = [b，a]`是解构赋值，右边，创建了一个数组`[b, a]`，即`[2,1]`。这个数组`2`被赋值了给`a`，1被赋值给了`b`

``````let zero = 2;
let one = 1;
let two = 0;

[zero, one, two] = [two, one, zero];

zero; // => 0
one;  // => 1
two;  // => 2
``````

## 2. 访问数组中元素

``````const colors = [];

let firstColor = 'white';
if (colors.length > 0) {
firstColor = colors[0];
}

firstColor; // => 'white'
``````

``````const colors = [];

const [firstColor = 'white'] = colors;

firstColor; // => 'white'
``````

`const [firstColor = 'white'] = colors` 解构将`colors`数组的第一个元素赋给`firstColor`变量。如果数组在索引`0`处没有任何元素，则分配“`white`”默认值。

``````const colors = [];

const [, secondColor = 'black'] = colors;

secondColor; // => 'black'
``````

## 3.不可变操作

``````const numbers = [1, 2, 3];

const [, ...fooNumbers] = numbers;

fooNumbers; // => [2, 3]
numbers; // => [1, 2, 3]
``````

`numbers` 数组没有发生变化，保持操作不变性。

``````const big = {
foo: 'value Foo',
bar: 'value Bar'
};

const { foo, ...small } = big;

small; // => { bar: 'value Bar' }
big; // => { foo: 'value Foo', bar: 'value Bar' }
``````

## 4.解构 iterables

`movies`包含一个`movie`对象列表。在解构`movies`时，将`title`作为字符串获取是非常棒的。让咱们实现一个自定义迭代器。

``````const movies = {
list: [
{ title: 'Heat' },
{ title: 'Interstellar' }
],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.list.length) {
const value = this.list[index++].title;
return { value, done: false };
}
return { done: true };
}
};
}
};

const [firstMovieTitle] = movies;
console.log(firstMovieTitle); // => 'Heat'

``````

`movies`对象通过定义`Symbol.iterator`方法来实现可迭代协议，迭代器迭代`title`

## 5.解构动态属性

``````const movie = { title: 'Heat' };

const { title } = movie;

title; // => 'Heat'
``````

`const {title} = movie`创建一个变量`title`，并将属性`movie.title`的值赋给它。

``````function greet(obj, nameProp) {
const { [nameProp]: name = 'Unknown' } = obj;
return `Hello, \${name}!`;
}

greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!'
greet({ }, 'name'); // => 'Hello, Unknown!'

``````

`greet()`内部，解构赋值`const {[nameProp]：name ='Unknown'} = obj`使用方括号的形式 `[nameProp]`读取动态属性名称，`name`变量接收动态属性值。

## 交流

https://github.com/qq44924588...

40948 人关注
456 篇文章