JavaScript对象可以看做是属性的集合,我们经常会检测集合中成员的所属关系——判断某个属性是否存在某个对象中。
可以通过 in
运算符 或hasOwnPreperty()
或 propertyIsEnumerable()
方法来完成这个工作。
in
in运算符的左侧是属性名(字符串),右侧是对象。如果对象的自有属性或继承属性中包含这个属性则返回 true
var o = {x: 1};
'x' in o; // true: 'x'是o的属性
'y' in o; // false: 'y'不是o的属性也不是o的继承属性
'toString' in o; // true: o 继承toString 属性
hasOwnProperty()
对象的 hasOwnProperty()
方法用来检测给定的名字是否是对象的自有属性,如果是自有属性才会返回 true
var o = {x: 1};
o.hasOwnProperty('x'); // true: o有一个自有属性x
o.hasOwnProperty('y'); // false: y不是o的自有属性
o.hasOwnProperty('toString'); // false: toString不是o的自有属性
propertyIsEnumerable()
propertyIsEnumerable()
是 hasOwnProperty()
的增强版,只有在检测到是自有属性且这个属性的可枚举性(enumerable attribute)为 true
时它才返回 true