Home  >  Article  >  Web Front-end  >  How to Check for Object Property Existence Using a Variable in JavaScript?

How to Check for Object Property Existence Using a Variable in JavaScript?

DDD
DDDOriginal
2024-10-31 18:35:29895browse

How to Check for Object Property Existence Using a Variable in JavaScript?

Checking Object Property Existence with a Variable

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn