解构
1.数组解构
const [a,b,[c,d],e] = [1,2,[3,4],5]
2.元素解构
console.log(...document.getElementsByTagName('div'))
3.实现迭代器接口的数据-解构
const obj = { *[Symbol.iterator](){ yield 1 yield 2 yield 3 yield 4 yield 8 } } console.log(...obj)
4.解构赋默认值
const [a1=1,b1=2] = [null,undefined] console.log(a1,b1)
5.对象解构
const {name,age,title} = {name:'zhangsan',age:10}
6.定义别名
const {name:nm} = {name:'zhangsan',age:10}
7.嵌套解构
const obj1 = { color:'red', shape:{ width:10, height:20, size(){ console.log(this) console.log(this.width * this.height) } } } const {color,shape,shape:{width,height,size}} = obj1 shape.size()
8.解构时存储数据
let obj2 = {} let arr2 = [] ({name:obj2.name,num:arr2[0]} = {name:'zhangsan',num:10}) console.log(obj2,arr2)
9.除了null、undefined 其他数据均可被解构
const {toString} = NaN
10.字符串解构可以通过有object方式也可以通过Array方式
const [a1,a2] = 'apple'
const {split} = 'apple'
11.参数解构
// 参数解构 console.log([[1,2],[3,4],[5]].map(([a,b=20])=>{ return a+b })) // 函数参数解构、默认赋值 function demo({a,b} = {a:10,b:20}){ console.log(a+b) } demo({a:5,b:6}) demo()
12.解构应用 (解构是浅复制)
1.数据交换
2.导入模块和暴露接口
3.for of 循环解构参成员
4.函数参数默认配置项
5.解构服务器返回数据
6.函数参数和返回值解构
7.react的setState
8.vuex的mapState