对象析构是从对象或数组中获取或提取值的一种新的、更简洁的方法。假设有如下的对象: const employee = {
firstName: "Marko",
lastName: "Polo",
position: "Software Developer",
yearHired: 2017
};
从对象获取属性,早期方法是创建一个与对象属性同名的变量。这种方法很麻烦,因为我们要 为每个属性创建一个新变量。假设我们有一个大对象,它有很多属性和方法,用这种方法提取 属性会很麻烦。
var firstName = employee. firstName; var lastName = employee. lastName; var position =employee, position; var yearHired = employee. yearHired;
使用解构方式语法就变得简洁多了 :
{ firstName, lastName, position, yearHired } = employee;
我们还可以为属性取别名:
let { firstName: fName, lastName: lName, position, yearHired }= employee;
当然如果属性值为undefined时,我们还可以指定默认值:
let { firstName = "Mark", lastName: lName, position, yearHired } = employee;

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.