js屬性對象的propertyIsEnumerable方法
定義
每個對象都有一個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的區別
hasOwnProperty()方法檢驗是否為自有屬性。propertyIsEnumberable()方法,可以確定對象中的指定屬性(除了通過原型鏈繼承的屬性)是否可以由for...in循環枚舉。
[完]
感謝您的認真閱讀,更多內容請查看:
出處:http://www.rzrgm.cn/weiqinl
個人主頁http://weiqinl.com
github: weiqinl
簡書:weiqinl
您的留言討論是對博主最大的支持!
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
出處:http://www.rzrgm.cn/weiqinl
個人主頁http://weiqinl.com
github: weiqinl
簡書:weiqinl
您的留言討論是對博主最大的支持!
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

浙公網安備 33010602011771號