Object.propertyIsEnumerable()
方法用于检查给定属性是否是该对象自身的可枚举属性。
示例
let arr = [1, 2, 3, 4];
// check whether the element at
// index 0 is enumerable or not
console.log(arr.propertyIsEnumerable(0));
// Output: true
// check whether length is enumerable or not
console.log(arr.propertyIsEnumerable(arr.length));
// Output: false
propertyIsEnumerable() 语法
propertyIsEnumerable()
方法的语法是:
obj.propertyIsEnumerable(prop)
其中,obj 是需要检查其属性(prop)是否可枚举的对象。
propertyIsEnumerable() 参数
propertyIsEnumerable()
方法接受:
- prop - 要测试的属性名称
propertyIsEnumerable() 返回值
propertyIsEnumerable()
方法返回:
true
- 如果属性可枚举并且存在于对象中false
- 如果属性不可枚举或者不存在于对象中
注意: 每个对象都有一个 propertyIsEnumerable()
方法。此方法可以确定对象中的指定属性是否可以被 for...in 循环枚举。
示例 1:JavaScript Object.propertyIsEnumerable()
// create a simple object
let obj = {
message: "Hello World!",
};
// check if prop is enumerable
console.log(obj.propertyIsEnumerable("message"));
// Output: true
// check a property that does not exist in the object
console.log(obj.propertyIsEnumerable("random"));
// Output: false
在上面的示例中,propertyIsEnumerable()
方法返回 true
作为输出,因为属性 message 存在于对象 obj 中并且是可枚举的。
然而,在检查不存在的属性 random 是否可枚举时,我们得到 false
作为输出。
示例 2:propertyIsEnumerable() 与内置对象
console.log(Math.propertyIsEnumerable("random"));
// Output: false
console.log(Math.propertyIsEnumerable("E"));
// Output: false
在上面的示例中,当检查 random 和 E 是否可枚举时,propertyIsEnumerable()
方法返回 false
作为输出。
在这里,random 和 E 是 JavaScript 中内置的 Math 对象的两个属性。
注意: 用户创建的属性通常是可枚举的(除非显式设置为 false
),而大多数内置属性默认是不可枚举的。
另请阅读