Say you have an object with some properties:
假设您有一个具有某些属性的对象:
const person = {
firstName: 'Tom',
lastName: 'Cruise',
actor: true,
age: 57
}
You can extract just some of the object properties and put them into named variables:
您可以提取一些对象属性,然后将它们放入命名变量中:
const { firstName, age } = person
Now we have 2 new variables, firstName
and age
, that contain the desired values:
现在,我们有2个新变量firstName
和age
,其中包含所需的值:
console.log(firstName) // 'Tom'
console.log(age) // 54
The value assigned to the variables does not depend on the order we list them, but it’s based on the property names.
分配给变量的值不取决于我们列出它们的顺序,而是基于属性名称。
You can also automatically assign a property to a variable with another name:
您还可以自动将属性分配给具有其他名称的变量:
const { firstName: name, age } = person
Now instead of a variable named firstName
, like we had in the previous example, we have a name
variable that holds the person.firstName
value:
现在,没有像上一个示例中那样名为firstName
的变量,而是拥有一个保存person.firstName
值的name
变量:
console.log(name) // 'Tom'
翻译自: https://flaviocopes.com/javascript-object-destructuring/