什么是描述符(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}