In JavaScript, verifying the presence of an object property using a variable can be a common task. However, directly using the variable as the property name leads to undefined results.
Example:
<code class="js">var myObj; myObj.prop = "exists"; var myProp = "p" + "r" + "o" + "p"; if (myObj.myProp) { alert("yes, i have that property"); }; // Undefined</code>
To overcome this, one must utilize methods that explicitly check property existence.
Solutions:
Option 1: hasOwnProperty
<code class="js">var myProp = 'prop'; if (myObj.hasOwnProperty(myProp)) { alert("yes, i have that property"); }</code>
Option 2: in operator (checks for both direct and inherited properties)
<code class="js">var myProp = 'prop'; if (myProp in myObj) { alert("yes, i have that property"); }</code>
Option 3: Direct in operator usage (checks only for direct properties)
<code class="js">if ('prop' in myObj) { alert("yes, i have that property"); }</code>
Note: hasOwnProperty does not check inherited properties, while the in operator does.
The above is the detailed content of How to Check for Object Property Existence Using a Variable in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!