# JavaScript 解构赋值实用指南

·  阅读 3923

## 一、基本概念

``````const student = {
name: 'ZhangSan',
age: 18,
scores: {
math: 19,
english: 85,
chinese: 100
}
};

function displayInfo(student) {
console.log('name:', student.name);
console.log('math:', student.scores.math);
console.log('english:', student.scores.english);
console.log('chinese:', student.scores.chinese);
}

displayInfo(student);

``````function displayInfo(student) {
const { name, scores: {math, english, chinese} } = student;
console.log('name:', name);
console.log('math:', math);
console.log('english:', english);
console.log('chinese:', chinese);
}

## 二、解构分类

• 对象解构
• 数组解构

### 1. 对象的解构赋值

``````let obj =  {x: 1, y: 2, z: 3};

let {x: a, y: b, z: c} = obj;
console.log(a, b, c)

let {x, y, z} = obj;
console.log(x, y, z)

• 第一种（第3行）是对象解构的完整形式，对象的每个属性都将被分配一个变量，其中冒号前面的是源对象中的属性，冒号后面的是要赋值属性;
• 第二种（第5行）是对象解构的简写形式，对象的属性与要分配的属性一致时可以使用这种形式。

``````let obj =  {x: 1, y: 2, z: 3};

let x = 0, y = 0, z = 0;

({x, y, z} = obj)
console.log(x, y, z)

``````const person = {
name: 'ZhangSan',
height: 180
};

const { name, height, age = 25 } = person;

console.log(name, height, age);

``````const {x = 2} = {x: undefined};
console.log(x);    // 2

### 2. 数组的解构赋值

#### （1）字符串

``````let message = 'Hello';
let [a, b] = message;
let [x, y, ...z] = message;

console.log(a, b);        // H e
console.log(x, y, z);     // H e ['l', 'l', 'o']

#### （2）数组

``````let numbers = [1, 2, 3];
let [x, y, z] = numbers;

console.log(x, y, z);    // 1 2 3

#### （3）集合

``````let set = new Set().add('foo').add('bar');
let [a, b] = set;

console.log(a, b);      // foo bar

#### （4）Map

``````let map = new Map().set('a', 1).set('b', 2);
let [x, y] = map;

console.log(x, y);    // ["a", 1] ["b", 2]

``````const rgb = [200, 255, 100];

const [,, blue] = rgb;

console.log(blue);   // 100

``````const rgb = [200];

const [red = 255, green, blue = 255] = rgb;

console.log(`R: \${red}, G: \${green}, B: \${blue}`);

``````
let red = 100, green = 200, blue = 50;

const rgb = [200, 255, 100];

[red, green] = rgb;

console.log(`R: \${red}, G: \${green}, B: \${blue}`);

``````const [x = 1] = [undefined];
console.log(x);    // 1

``````function foo() {
return 1;
}

let obj1 = {x: 2};
let obj2 = {x: undefined};

let {x=foo()} = obj1;
console.log(x);     // 2

let {x=foo()} = obj2;
console.log(x);     // 1

``````let [greeting,...intro] = ["Hello", "I" , "am", "CUGGZ"];

console.log(greeting);  // "Hello"
console.log(intro);     // ["I", "am", "CUGGZ"]

## 三、嵌套解构

``````const student = {
name: 'ZhangSan',
age: 18,
scores: {
math: 19,
english: 85,
chinese: 100
}
};

const { name, scores: {math, english, chinese} } = student;

``````let numbers = [1, [2, 3, 4], 5];
let [a, [b, c, d], e] = numbers;
console.log(a, b, c, d, e); // 1 2 3 4 5

## 五、使用技巧

### 1. 函数解构

#### （1）解构函数参数

``````function foo([a, b]) {
console.log(a + b);
}
foo([1, 2]);       // 3

function bar({x, y}) {
console.log(x, y);
}
foo({x: 1, y: 2}); // 1 2

``````function getStudentInfo() {
return {
name: 'ZhangSan',
age: 18,
scores: {
math: 19,
english: 85,
chinese: 100
}
};
}
const { name, scores: {math, english, chinese} } = getStudentInfo();
console.log(name, math, english, chinese);

### 2. 循环中的解构

``````const students = [
{
'name': 'ZhangSan',
},
{
'name': 'LiSi',
},
{
'name': 'WangWu',
}
];

}

### 3. 动态属性解构

``````getStudentInfo('name');
getStudentInfo('age');

``````const getStudentInfo = key => {
const {[key]: value} = student;
return value;
}

### 4. 交换变量

``````let width = 300;
let height = 400;

let temp = width;
width = height;
height = temp;

console.log(width, height)

``````let width = 300;
let height = 400;

[width, height] = [height, width];

console.log(width, height)

### 5. 数组拷贝

``````const rgb = [200, 255, 100];

const [...newRgb] = rgb;
// 等同于 const newRgb = [...rgb]

console.log(newRgb)