主要保留一些重点特性和复杂用法,其他详见 JS现代教程
# 数组解构
# 基本语法
let [item1 = default, item2, ...rest] = array
# 忽略不需要的元素
// 不需要第二个元素
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
# 可迭代对象解构
实际上,我们可以将其与任何可迭代对象一起使用,而不仅限于数组
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);
我们可以将 .entries() 方法与解构语法一同使用,来遍历一个对象的“键—值”对
let user = {
name: "John",
age: 30
};
// 循环遍历键—值对
for (let [key, value] of Object.entries(user)) {
alert(`${key}:${value}`); // name:John, then age:30
}
对于 map 对象也类似:
let user = new Map();
user.set("name", "John");
user.set("age", "30");
for (let [key, value] of user) {
alert(`${key}:${value}`); // name:John, then age:30
}
# 交换变量值
let guest = "Jane";
let admin = "Pete";
// 交换值:让 guest=Pete, admin=Jane
[guest, admin] = [admin, guest];
alert(`${guest} ${admin}`); // Pete Jane(成功交换!)
这里我们创建了一个由两个变量组成的临时数组,并且立即以交换了的顺序对其进行了解构。
我们可以用这种方式交换两个以上的变量。
# "..."
如果我们不只是要获得第一个值,还要将后续的所有元素都收集起来 — 我们可以使用三个点 "..."
来再加一个参数来接收“剩余的”元素
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(name1); // Julius
alert(name2); // Caesar
// 请注意,`rest` 的类型是数组
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2
# 对象解构
# 基本语法
let {prop : varName = default, ...rest} = object
- 结构的 prop 必须在 右侧的对象中有对应一样名字的属性,因为是按照名字匹配
prop : varName
代表实际生成的变量是varName
,并不会产生叫做prop
的变量default
是默认值
# 先定义变量后赋值
这种情况下会报错,问题在于 JavaScript 把主代码流(即不在其他表达式中)的 {...}
当做一个代码块:
let title, width, height;
// 这一行发生了错误
{title, width, height} = {title: "Menu", width: 200, height: 100};
正确写法,加上括号就好了:
let title, width, height;
// 现在就可以了
({title, width, height} = {title: "Menu", width: 200, height: 100});
alert( title ); // Menu
#
# "..."
用 ...
生成的变量是一个对象
let options = {
title: "Menu",
height: 200,
width: 100
};
// title = 名为 title 的属性
// rest = 存有剩余属性的对象
let {title, ...rest} = options;
// 现在 title="Menu", rest={height: 200, width: 100}
alert(rest.height); // 200
alert(rest.width); // 100
# 复杂用法
# 嵌套解构
如果一个对象或数组嵌套了其他的对象和数组,我们可以在等号左侧使用更复杂的模式(pattern)来提取更深层的数据。
let options = {
size: {
width: 100,
height: 200
},
items: ["Cake", "Donut"],
extra: true
};
// 为了清晰起见,解构赋值语句被写成多行的形式
let {
size: { // 把 size 赋值到这里
width,
height
},
items: [item1, item2], // 把 items 赋值到这里
title = "Menu" // 在对象中不存在(使用默认值)
} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
alert(item1); // Cake
alert(item2); // Donut
注意,这里并不会产生 size
和 items
变量,他们仅仅是过程中用来匹配值