【ES8系列】获取 Object 对象属性描述符

什么是描述符(descriptor)? 

// 业务场景:从接口拿到学生信息数据,某些学生退学,所以展示时需要跳过
const data = {
  PortLand: '78/50',
  DuLin: '88/52',
  Lima: '58/40'
}
// 使指定数据不可枚举
Object.defineProperty(data, 'Lima', {
  enumerable: false
})
console.log(Object.keys(data)) // ["PortLand", "DuLin"]

defineProperty 的第三个参数就是描述符(descriptor)。这个描述符包括几个属性:

  • value [属性的值]
  • writable [属性的值是否可被改变]
  • enumerable [属性的值是否可被枚举]
  • configurable [描述符本身是否可被修改,属性是否可被删除]

Object.getOwnPropertyDescriptors() 

获取对象的所有属性的描述符

// 业务场景:从接口拿到学生信息数据,某些学生退学,所以展示时需要跳过
const data = {
  PortLand: '78/50',
  DuLin: '88/52',
  Lima: '58/40'
}
// 使指定数据不可枚举
Object.defineProperty(data, 'Lima', {
  enumerable: false
})
console.log(Object.keys(data)) // ["PortLand", "DuLin"]
console.log(Object.getOwnPropertyDescriptors(data))
// {PortLand: {…}, DuLin: {…}, Lima: {…}}
// DuLin:
//     configurable: true
//     enumerable: true
//     value: "88/52"
//     writable: true
//     __proto__: Object
// Lima:
//     configurable: true
//     enumerable: false
//     value: "58/40"
//     writable: true
//     __proto__: Object
// PortLand:
//     configurable: true
//     enumerable: true
//     value: "78/50"
//     writable: true
//     __proto__: Object
// __proto__: Object

Object.getOwnPropertyDescriptor() 

获取对象指定属性的描述符

const data = {
  PortLand: '78/50',
  DuLin: '88/52',
  Lima: '58/40'
}
// 使指定数据不可枚举
Object.defineProperty(data, 'Lima', {
  enumerable: false
})
console.log(Object.keys(data)) // ["PortLand", "DuLin"]
console.log(Object.getOwnPropertyDescriptor(data, 'Lima')) 
//{value: "58/40", writable: true, enumerable: false, configurable: true}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值