ES6 引入了解构表达式,它提供了一种简洁、优雅的方式来提取数组和对象的值。解构表达式可以用于:
-
从数组中提取值
-
从对象中提取属性值
-
设置默认值
-
嵌套解构
1. 从数组中提取值
const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
在这个例子中,我们使用解构表达式从数组 [1, 2, 3]
中提取值,并将它们分别赋值给变量 a
、b
和 c
。
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
在这个例子中,first
和 second
分别被赋值为数组中的第一个和第二个元素。...rest
收集了剩余的元素,并将它们存储在名为 rest
的数组中。
2. 从对象中提取属性值
const { name, age } = { name: "John", age: 30 };
console.log(name); // John
console.log(age); // 30
在这个例子中,我们使用解构表达式从对象 { name: "John", age: 30 }
中提取属性 name
和 age
的值,并将它们分别赋值给变量 name
和 age
。
3. 设置默认值
const [a, b = 2] = [1];
console.log(a); // 1
console.log(b); // 2
在这个例子中,我们使用了默认值 b = 2
。由于数组 [1]
只有一个元素,b
将被赋值为默认值 2
。
4. 嵌套解构
const { name, age, address: { street } } = { name: "John", age: 30, address: { street: "Main Street" } };
console.log(name); // John
console.log(age); // 30
console.log(street); // Main Street
在这个例子中,我们使用了嵌套解构来提取嵌套对象 address
的属性 street
的值。
解构表达式的优势:
- 简洁易读: 解构表达式使代码更加简洁易读,特别是处理复杂数据结构时。
- 提高代码可维护性: 减少了变量声明和赋值的代码量,提高了代码的可维护性。
- 提高代码效率: 解构表达式可以提高代码效率,因为它可以避免重复的变量声明和赋值操作。