An array in JavaScript is an ordered collection of values, and you can iterate over them using various methods. Here are the key approaches:
This method uses implicit iterators and is ideal for simple, asynchronous operations:
const a = ["a", "b", "c"]; for (const element of a) { console.log(element); } // Output: // a // b // c
This method calls a callback function for each element in the array:
a.forEach(element => { console.log(element); }); // Output: // a // b // c
This traditional method provides direct access to the element and its index:
for (let index = 0; index < a.length; ++index) { const element = a[index]; console.log(element); } // Output: // a // b // c
For-in should be used with safeguards to avoid potential issues with inherited properties:
for (const propertyName in a) { if (a.hasOwnProperty(propertyName)) { const element = a[propertyName]; console.log(element); } } // Output: // a // b // c
In addition to genuine arrays, the approaches can be applied to array-like objects like arguments, iterable objects (ES2015 ), DOM collections, and so on. Keep in mind the following considerations:
The above is the detailed content of How Can I Iterate Over an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!