内容目录
propertyIsEnumerable()
方法返回布尔值,该值指示指定属性是否为对象的一部分以及该属性是否是可枚举的。
该方法属于Object
对象,由于JS中的所有对象都是Object的实例,因此几乎所有的实例对象都可以使用该方法。所有主流浏览器均支持该方法。
语法
object.propertyIsEnumerable( propertyName )
参数
参数 | 描述 |
---|---|
propertyName | String类型指定的属性名称 |
返回值
propertyIsEnumerable()
方法的返回值为Boolean类型,该值指示指定属性是否为对象的一部分以及该属性是否是可枚举的(只有这两个条件同时满足才返回true
)。
示例&说明
如果propertyName
存在于object
中且可以使用for...in
循环遍历出来,则propertyIsEnumerable()
方法将返回true
。如果object
不具有所指定名称的属性或者所指定的属性不是可枚举的,则propertyIsEnumerable()
方法将返回false
。
通常,预定义的属性不是可枚举的,而用户定义的属性总是可枚举的。不过有些属性虽然可以通过for...in
循环遍历到,但因为它们不是自身属性,而是从原型链上继承的属性,所以该方法也会返回false
。
var o = { "name": "张三" };
document.writeln( o.propertyIsEnumerable("name") ); // true
// 对象的constructor为内置属性
document.writeln( o.propertyIsEnumerable("constructor") ); // false
var arr = [1, 2];
document.writeln( arr.propertyIsEnumerable( 1 ) ); // true
// 数组的length为内置属性
document.writeln( arr.propertyIsEnumerable( "length" ) ); // false
用户自定义的对象,通过原型"继承"获得的属性,使用该方法也返回false
。
function Site(){
this.name = "CodePlayer";
this.url = "https://codeplayer.vip/";
this.sayHello = function(){
document.writeln("欢迎来到" + this.name);
};
}
// 添加原型属性
Site.prototype.engine = "PHP";
Site.prototype.sayHi = function(){
document.writeln("欢迎访问" + this.url);
};
var site = new Site();
document.writeln( site.propertyIsEnumerable("name") ); // true
document.writeln( site.propertyIsEnumerable("sayHello") ); // true
// 原型上继承来的属性均为false
document.writeln( site.propertyIsEnumerable("engine") ); // false
document.writeln( site.propertyIsEnumerable("sayHi") ); // false
0 条评论
撰写评论