1.可以通过in和hasOwnProperty(..)判断属性是否存在于对象中
var myObject={
a:2
}
console.log("a" in myObject);//true
console.log("b" in myObject);//false
console.log(myObject.hasOwnProperty('a'));//true
console.log(myObject.hasOwnProperty('b'));//false
in可以检查属性是否在对象及其[[Prototype]]原型链中
hasOwnProperty(..)只会检查属性是否在对象中,不会检查[[Prototype]]原型链
1.1对象中虽然存在该属性,但是不一定可以枚举出来
可枚举就是可以出现在对象属性的遍历中
var myObject={};
Object.defineProperty(
myObject,
"a",
{
enumerable:false,
value:2
}
)
console.log('a' in myObject);//true
console.log(myObject.hasOwnProperty('a'));//true
for (var i in myObject) {
console.log(i,myObject[i]);
}//
1.2通过propertyIsEnumerable(..)检查属性名是否可以枚举
Object.keys(..)返回数组,可以枚举的直接属性
Object.getOwnPropertyNames(..)返回数组,任何直接属性
var myObject={};
Object.defineProperty(
myObject,
"a",
{
enumerable:false,
value:2
}
)
Object.defineProperty(
myObject,
"b",
{
enumerable:true,
value:2
}
)
myObject.propertyIsEnumerable('a');//false
myObject.propertyIsEnumerable('b');//true
console.log(Object.keys(myObject));//["a"]
console.log(Object.getOwnPropertyNames(myObject));//["a", "b"]