I generally use the typeof
operator:
(我通常使用typeof
运算符:)
if (typeof obj.foo !== 'undefined') {
// your code here
}
It will return "undefined"
either if the property doesn't exist or its value is undefined
.
(如果该属性不存在或其值是undefined
,它将返回"undefined"
。)
(See also: Difference between undefined
and not being defined. )
((另请参见: undefined
和undefined
之间的区别。 ))
There are other ways to figure out if a property exists on an object, like the hasOwnProperty
method:
(还有其他方法hasOwnProperty
对象上是否存在属性,例如hasOwnProperty
方法:)
if (obj.hasOwnProperty('foo')) {
// your code here
}
And the in
operator:
(和in
运算符:)
if ('foo' in obj) {
// your code here
}
The difference between the last two is that the hasOwnProperty
method will check if the property exist physically on the object (the property is not inherited).
(最后两者之间的区别是, hasOwnProperty
方法将检查属性的对象上实际存在(该财产不继承)。)
The in
operator will check on all the properties reachable up in the prototype chain, eg:
(in
运算符将检查原型链中所有可达的属性,例如:)
var obj = { foo: 'bar'};
obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true
As you can see, hasOwnProperty
returns false
and the in
operator returns true
when checking the toString
method, this method is defined up in the prototype chain, because obj
inherits form Object.prototype
.
(如您所见,在检查toString
方法时, hasOwnProperty
返回false
, in
运算符返回true
,该方法在原型链中定义,因为obj
继承了Object.prototype
形式。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…