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
发布了26 篇原创文章 · 获赞 0 · 访问量 608

猜你喜欢

转载自blog.csdn.net/weixin_43856797/article/details/103972108