Object 检测属性
检测一个属性是否属于某个对象。常用的方式主要有3种:
-
in
检测某属性是否是某对象的自有属性或者是继承属性
var obj = { name: 'zhangsan', age: 18, school: 'xx大学' } //in运算符的左侧为属性名称,右侧为对象 console.log('name' in obj); //true console.log('age' in obj); //true console.log('gender' in obj); //false //如果用in判断一个属性存在,这个属性不一定是obj的,它可能是obj继承得到的,如: 'toString' in obj; // true 因为toString定义在object对象中,而所有对象最终都会在原型链上指向object,所以obj也拥有toString属性。
-
Object.prototype.hasOwnProperty()
检测给定的属性是否是对象的自有属性,对于继承属性将返回false
var obj = { name: 'zhangsan', age: 18, school: 'xx大学' } console.log(obj.hasOwnProperty('name')); //true console.log(obj.hasOwnProperty('age')); //true console.log(obj.hasOwnProperty('toString')); //false,toString为继承属性 console.log(obj.hasOwnProperty('gender')); //false
-
Object.prototype.propertyIsEnumerable()
propertyIsEnumerable()是hasOwnProperty()的增强版,除了是自身属性外,还要求是可枚举属性,即我们创建的属性。
var obj = { name: 'zhangsan', age: 18, school: 'xx大学' } console.log(obj.propertyIsEnumerable('name')); //true console.log(obj.propertyIsEnumerable('age')); //true console.log(obj.propertyIsEnumerable('toString')); //false,不可枚举 console.log(obj.propertyIsEnumerable('gender')); //false