Home > Web Front-end > JS Tutorial > How Can I Iterate Over an Array in JavaScript?

How Can I Iterate Over an Array in JavaScript?

Patricia Arquette
Release: 2024-12-26 16:02:09
Original
857 people have browsed it

How Can I Iterate Over an Array in JavaScript?

Loop (for each) over an Array in JavaScript

An array in JavaScript is an ordered collection of values, and you can iterate over them using various methods. Here are the key approaches:

Specific to Genuine Arrays

1. For-of Loop (ES2015 )

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
Copy after login

2. ForEach and Related (ES5 )

This method calls a callback function for each element in the array:

a.forEach(element => {
    console.log(element);
});
// Output:
// a
// b
// c
Copy after login

3. Simple For Loop

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
Copy after login

4. For-in (Use with Caution)

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
Copy after login

Generalizing to Array-Like Objects

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:

  • Arguments Object: Use a for-of loop or an explicit iterator, as for-each and for loops won't work correctly.
  • Iterable Objects: Use a for-of loop or explicit iterator.
  • DOM Collections: Use a for-of loop or explicit iterator.

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!

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