Home >Web Front-end >JS Tutorial >How Do I Iterate Over JavaScript Objects Using Loops?

How Do I Iterate Over JavaScript Objects Using Loops?

DDD
DDDOriginal
2024-12-25 06:42:13395browse

How Do I Iterate Over JavaScript Objects Using Loops?

Looping and Enumerating JavaScript Objects

Enumerating or iterating over the elements of a JavaScript object is a common task. Consider the following object:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Traversing Keys and Values Using for-in Loop:

The for-in loop allows you to iterate over the enumerable properties of an object. Here's how you would use it with the p object:

for (var key in p) {
    console.log(key + " -> " + p[key]);
}

This loop will print the following pairs:

  • p1 -> value1
  • p2 -> value2
  • p3 -> value3

Handling Inherited Properties (Optional):

It's important to note that by default, the for-in loop will iterate over inherited properties as well. If you only want to list properties directly owned by the object, you can use hasOwnProperty:

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

The above is the detailed content of How Do I Iterate Over JavaScript Objects Using Loops?. 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