什么是JavaScript中的对象分解?

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个新变量firstNameage ,其中包含所需的值:

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值