Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

什么是对象解构? #273

Open
Sogrey opened this issue Sep 7, 2020 · 0 comments
Open

什么是对象解构? #273

Sogrey opened this issue Sep 7, 2020 · 0 comments
Labels
模块化&ES5、ES6 模块化&ES5、ES6

Comments

@Sogrey
Copy link
Owner

Sogrey commented Sep 7, 2020

对象析构是从对象或数组中获取或提取值的一种新的、更简洁的方法。假设有如下的对象:

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;
@Sogrey Sogrey added the 模块化&ES5、ES6 模块化&ES5、ES6 label Sep 7, 2020
@Sogrey Sogrey added this to javascript in Web面经题 Sep 7, 2020
@Sogrey Sogrey moved this from javascript to 模块化&ES5、ES6 in Web面经题 Sep 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
模块化&ES5、ES6 模块化&ES5、ES6
Projects
Web面经题
模块化&ES5、ES6
Development

No branches or pull requests

1 participant