# 在 Javascript 中如何解构数组和对象

## 数组解构

``````const arr = [1, 2, 3];
const a = arr[0]; // a = 1
const b = arr[1]; // b = 2
const c = arr[2]; // c = 3
``````

``````const arr = [1, 2, 3];
const [a, b, c] = arr;
// a = 1, b = 2, c = 3
``````

``````const arr = [1, 2, 3, 4];
// a = 1, b = 2
const [a, b] = arr;
// x = 2, y = 4
const [ , x,  , y] = arr;
``````

### 使用解构交换值

``````let a = 10, b = 20;

// Old way
let temp = a;
a = b;
b = temp;   // a = 20, b = 10

// Using destructuring
[a, b] = [b, a];   // a = 20, b = 10
``````

### 从函数调用中接收多个值

``````const restaurant = {
name: 'La\' Pinoz Pizza',
categories: ['Italian', 'Vegetarian', 'Non-Vegetarian', 'Organic'],
order: function(starterIndex, mainIndex) {
}
} ``````

`restaurant`​对象的 order 属性是一个函数，它接受两个参数并返回一个包含两个值的数组。我们可以在这里使用解构，将 Array 的元素直接赋值给变量。

``````const [starter, mainCourse] = restaurant.order(2,1);
console.log(starter, mainCourse);
// output: Pastries Pasta
``````

### 嵌套解构

``````const nested = [1, 2, [3, 4]];
const [a, b, c] = nested;  // a = 1, b = 2, c = [3, 4]
const [x, , [y, z]] = nested; // x = 1, y = 3, z = 4
``````

### 默认值

``````const unknownArray = [1, 5, 9];
const [a, b, c, d] = unknownArray;
console.log(a,b,c,d);
// Output: 1 5 9 undefined
``````

## 对象解构

``````const restaurant = {
nameOfRestaurant: 'La\' Pinoz Pizza',
categories: ['Italian', 'Vegetarian', 'Non-Vegetarian', 'Organic'],
order: function(starterIndex, mainIndex) {
},
openingHours: {
thu: {
open: 11,
close: 22
},
fri: {
open: 10,
close: 23
},
sat: {
open: 11,
close: 23
}
}
}
``````

``````const {nameOfRestaurant, openingHours, mainMenu} = restaurant;
console.log('Name: ', nameOfRestaurant);
console.log('Opening Hours: ', openingHours);

// Output:
// Name:  La' Pinoz Pizza
// Opening Hours:  {
//   thu: { open: 11, close: 22 },
//   fri: { open: 10, close: 23 },
//   sat: { open: 11, close: 23 }
// }
// Main Menu:  [ 'Pizza', 'Pasta', 'Risotto' ]
``````

### 使用不同的变量名

``````const {nameOfRestaurant: name, openingHours: timing, mainMenu: menu} = restaurant;
console.log('Name: ', name);
console.log('Opening Hours: ', timing);
// We get the output similar to the above output.
``````

### 设置默认值

``````const {nameOfRestaurant: name = 'PizzaHut', menu = [ ]} = restaurant;
// Lets assume that the restaurant object has no property with name 'nameOfRestaurant',
// In this case the name becomes 'PizzaHut'.
// On the other hand there is no menu property so menu is assigned with empty array.
``````

### 变异值

``````let a = 11;
let b = 23;
let obj = { a: 120, b: 34 };
({ a, b } = obj);  // Important line
console.log(a, b);  // a = 120, b = 34``````

0 人点赞