每一个对象都有一个propertyIsEnumerable()
方法。此方法返回一个布尔值,代表指定的属性是不是可枚举。html
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)浏览器
翻译:oop
此方法能够肯定对象中的指定属性是否能够由
for ... in
循环枚举,但经过原型链继承的属性除外。网站
我理解的意思,不知道对不对:
此方法,能够肯定对象中的指定属性(除了经过原型链继承的属性)是否能够由for...in
循环枚举。
也就是说:
for...in
循环出来的属性,除了经过原型链继承的属性不是可枚举,其余都是可枚举属性。this
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对象的可枚举属性到底有多少个呢?prototype
var arr = [] for(let i in window) { if(window.propertyIsEnumerable(i)) { arr.push(i) } } console.log(arr.length)
这个长度,在每一个网站的值都是不同的,由于他们会各自往window上添加全局属性。我看到最少的可枚举属性值个数为195翻译
hasOwnProperty()
方法检验是否为自有属性。propertyIsEnumberable()
方法,能够肯定对象中的指定属性(除了经过原型链继承的属性)是否能够由for...in
循环枚举。 [完]