判断一个属性是否属于一个属性集合可以用in运算符、hasOwnPreperty()、propertyIsEnumerable()等方法完成。
三者的用法与区别
1.in运算符。
var a = {x:1};
"x" in a; //true
"y" in a; //false
in 不仅可以检测自有属性,而且可以检测a继承来的属性。只要具备就返回true,否则返回false;
2.hasOwnPreperty()
a.hasOwnPreperty("x"); //true
a.hasOwnPreperty("y"); //false
hasOwnPreperty()只能检测自有属性。对于继承属性,只能返回false;
3.propertyIsEnumerable()
a.propertyIsEnumerable("x"); //true
a.propertyIsEnumerable("y"); //false
propertyIsEnumerable()只能检测自有属性,并且此属性是可枚举的属性才返回true,否则返回false。
例如:Object.prototype.propertyIsEnumerable("toString"); //false
因为"toString"虽然是Object的自有属性,但是"toString"是不可枚举的所以返回false