Home >Web Front-end >JS Tutorial >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:
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!