解构的作用:简单来说就是简化信息提取,在编码过程中,我们经常定义许多对象和数组,然后有组织地从中提取相关的信息片段。ES6 中添加了可以简化这种任务的新特性:解构。解构是一种打破数据结构,将其拆分为更小部分的过程。
- 解构遵循匹配模式(匹配模式:只要等号两边的模式相同,左边的变量就会被赋予对应的值)
- 解构赋值规则:只要等号右边的值不是对象或数组,就先将其转为对象
- 解构默认值生效条件:属性值严格等于undefined
- 解构不成功时变量的值等于undefined
- undefined和null无法转为对象,因此无法进行解构
对象的解构赋值
对象解构的语法形式是在一个赋值操作符左边放置一个对象字面量,例如:
- 对象解构
- 形式:const { x, y } = { x: 1, y: 2 }
- console.log(x); //1
- console.log(y); //2
- 默认:const { x, y = 2 } = { x: 1 }
- console.log(x); //1
- console.log(y); //2 默认给y赋值2
- 改名:const { x, y: z } = { x: 1, y: 2 }
- console.log(x); //1
- console.log(y); //2
- console.log(z); //2 通过:改别名
这段代码中 对象中x的值被存储在变量 x中,对象中y的值被存储在变量y 中。
数组解构
- 规则:利用数组的索引解构赋值,不需要同名
- 形式:const [x, y] = [1, 2]
- console.log(x); //1
- console.log(y); //2
- 形式:const [x, ,y] = [1,2, 3]
- console.log(x); //1
- console.log(y); //3 //通过索引来赋值的
- 默认值:const [x, y = 2] = [1]
- console.log(x); //1
- console.log(y); //2
- 形式:const [x, ...y] = [1,2, 3]
- console.log(x); //1
- console.log(y); //[2,3] //通过...扩展运算符来赋值的
其他形式解构 (根源都来源于上述两种解构)
- 字符串解构:const [a, b, c, d, e] = "hello"
- 数值解构:const { toString: s } = 123
- 布尔解构:const { toString: b } = true
- 函数参数解构
- 数组解构:function Func([x = 0, y = 1]) {}
- 对象解构:function Func({ x = 0, y = 1 } = {}) {}
应用场景
- 交换变量值:[x, y] = [y, x]
- 返回函数多个值:const [x, y, z] = Func()
- 定义函数参数:Func([1, 2])
- 提取JSON数据:const { name, version } = packageJson
- 定义函数参数默认值:function Func({ x = 1, y = 2 } = {}) {}
- 遍历Map结构:for (let [k, v] of Map) {}