Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-11-01 11:07:02
Original
153 people have browsed it

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

How to Effectively Examine Object Property Existence Using a Property Name Variable

When working with JavaScript objects, determining whether a specific property exists is essential. However, what if you need to utilize a variable to hold the target property name?

In the provided example:

<code class="js">var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";

if(myObj.myProp){
    alert("yes, i have that property");
};</code>
Copy after login

The code attempts to check for the existence of a property named 'myprop', which does not exist. This is because JavaScript evaluates the expression as 'myObj.myprop' instead of 'myObj.prop'.

To successfully implement this logic, you can utilize several approaches:

Using hasOwnProperty

<code class="js">var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}</code>
Copy after login

hasOwnProperty verifies whether the object possesses a specific property, excluding inherited properties.

Using in Operator (ES5)

<code class="js">var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}</code>
Copy after login

in operator examines an object's enumerable properties, including both own and inherited ones.

Using Square Brackets (ES6)

<code class="js">if('prop' in myObj){
    alert("yes, i have that property");
}</code>
Copy after login

In ES6, square brackets can be used interchangeably with the in operator for property existence checking.

The above is the detailed content of How to Check for Property Existence Using a Variable Property Name in JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!