ES6:对象解构

当从一个对象中获取属性时,会进行这样操作:

const p1 = {
	name: 'Tom Shmith',
	age: 20,
	familly: {
		father: 'Jack Shmith',
		mother: 'Mary Shmith'
	}
}

const name = p1.name;//Tom Shmith
const age = p1.age;//20
const father = p1.familly.father;//Jack Shmith
const mother = p1.familly.mother;//Mary Shmith

es6可以通过对象解构非常简洁的书写,其结果与上面是一样的:

const { name, age } = p1;//name='Tom Shmith'  age=20
//嵌套内容
const { father ,mother } = p1.familly;
//father='Jack Shmith' mother='Mary Shmith'

还可以对解构的属性赋予新的变量名,需要在对应属性后面加冒号:

const { father: dad ,mother:mom } = p1.familly;
//dad='Jack Shmith'  mom='Mary Shmith'

如果获取对象中没有的属性,他会返回undefined

const { brother } = p1.familly;
console.log(brother); //undefined

可以直接在其中给它赋值,即创建了默认值:

const { brother = 'no brother' } = p1.familly;
console.log(brother); //no brother

但必须是undefined才可以,如果原属性是null或者false等,则会直接继承:

...
	brother: null,
...

const { brother = 'no brother' } = p1.familly;
console.log(brother); //null

...
	brother: undefined,
...

const { brother = 'no brother' } = p1.familly;
console.log(brother); //no brother
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值