How to determine whether an object has a given property in JavaScript
How can I determine whether an object x
has a defined property y
, regardless of the value of xy
?
I'm currently using
if (typeof(x.y) !== 'undefined')
but that seems a bit clunky. Is there a better way?
Object has property:
If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty()
:
if (x.hasOwnProperty('y')) {
// ......
}
Object or its prototype has a property:
You can use the in
operator to test for properties that are inherited as well.
if ('y' in x) {
// ......
}
If you want to know if the object physically contains the property @gnarf's answer using hasOwnProperty
will do the work.
If you're want to know if the property exists anywhere, either on the object itself or up in the prototype chain, you can use the in
operator.
if ('prop' in obj) {
// ...
}
Eg.:
var obj = {};
'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically
你可以修剪一下,就像这样:
if ( x.y !== undefined ) ...
链接地址: http://www.djcxy.com/p/700.html
上一篇: 什么是JavaScript垃圾收集?