具有Iterator接口的数据都可以解构赋值
数组的解构赋值
let arr = [1, 2, 3, 4] let [a, , c] = arr console.log(a, c) 1 3
let [a = 1, ...b] = [undefined, 2, 3, 4, 5, 6] console.log(a, b) 1 Array(5) [ 2, 3, 4, 5, 6 ]
上面代码的a设了默认值1,当a赋值严格等于undefined的时候,默认值才会生效
可以用rest参数作解构赋值
set类型的结构赋值
let [a, , , d] = new Set([1, 2, 3, 4]) console.log(a, d) 1 4
对象的解构赋值
let d = { a: 1, b: 2 }; [d.a, d.b] = [3, 4] console.log(d) Object { a: 3, b: 4 }
let d = { a: 1, b: 2 } for (let [k, v] of Object.entries(d)) { console.log(k, v) } a 1 b 2
let options = { title: 'menu', 100, height: 200 } // 如果变量名称跟属性名称一致,可以用简写的方式直接进行解构赋值 let { title, width, height } = options // 如果变量名想定义的跟属性名不一致,需要写清对照关系 let { title: title1, width1, height: height1 } = options console.log(title, width, height) console.log(title1, width1, height1) menu 100 200 menu 100 200
嵌套结构的解构赋值
let options = { title: { name: 'menu', id: 1 }, 100, height: 200 } let { title: { id }, ...otherAttr } = options console.log(id) console.log(otherAttr) 1 Object { 100, height: 200 }