首页 > 其他 > 详细

es6的解构赋值

时间:2020-05-18 19:48:48      阅读:40      评论:0      收藏:0      [点我收藏+]

具有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‘,
  width: 100,
  height: 200
}

// 如果变量名称跟属性名称一致,可以用简写的方式直接进行解构赋值
let { title, width, height } = options

// 如果变量名想定义的跟属性名不一致,需要写清对照关系
let { title: title1, width: 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
  },
  width: 100,
  height: 200
}

let { title: { id }, ...otherAttr } = options

console.log(id)
console.log(otherAttr)

1
Object { width: 100, height: 200 }

 

es6的解构赋值

原文:https://www.cnblogs.com/allenzhang-920/p/12907806.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!