js属性对象的propertyIsEnumerable方法

本文详细介绍了JavaScript中propertyIsEnumerable()方法的使用,包括如何判断对象属性是否可枚举、与hasOwnProperty()的区别等,并提供了具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义

每个对象都有一个propertyIsEnumerable()方法。此方法返回一个布尔值,表明指定的属性是否是可枚举。

This method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. (来源MDN)

翻译:

此方法可以确定对象中的指定属性是否可以由for ... in循环枚举,但通过原型链继承的属性除外。

我理解的意思,不知道对不对:
此方法,可以确定对象中的指定属性(除了通过原型链继承的属性)是否可以由for...in循环枚举。
也就是说:
for...in循环出来的属性,除了通过原型链继承的属性不是可枚举,其他都是可枚举属性。

用法举例

使用方法obj.propertyIsEnumerable(prop)来判断是否可枚举。

const obj = {};
const arr = [];
obj.name= 'weiqinl';
arr[0] = 2018;
console.log(obj.propertyIsEnumerable('name'));  // true
console.log(arr.propertyIsEnumerable(0)); // true
console.log(arr.propertyIsEnumerable('length')); // false

找出对象的可枚举属性

function Person(name,age) {
    this.name = name
    this.age = age
    this.say = function() {
        console.log('say hi')
    }
}
Person.prototype.where = 'beijing' // 在原型链上添加属性
var p = new Person('weiqinl', 18)  // 实例化一个对象
p.time = '2018'    // 在实例上添加属性
let arr = []
for(let i in p) {
    console.log(i, p.propertyIsEnumerable(i))
    p.propertyIsEnumerable(i)? arr.push(i) : ''
}
console.log(arr)
// name true
// age true
// say true
// time true
// where false
// (4) ["name", "age", "say", "time"]

浏览器的window对象的可枚举属性

window对象的可枚举属性到底有多少个呢?

var arr = []
for(let i in window) {
    if(window.propertyIsEnumerable(i)) {
        arr.push(i)
    }
}
console.log(arr.length) 

这个长度,在每个网站的值都是不一样的,因为他们会各自往window上添加全局属性。我看到最少的可枚举属性值个数为195

与hasOwnProperty的区别

  1. hasOwnProperty()方法检验是否为自有属性
  2. propertyIsEnumberable()方法,可以确定对象中的指定属性(除了通过原型链继承的属性)是否可以由for...in循环枚举。
    [完]

转载于:https://www.cnblogs.com/weiqinl/p/9572751.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值