Home > Web Front-end > JS Tutorial > How Can I Efficiently Iterate Through Arrays and Array-like Objects in JavaScript?

How Can I Efficiently Iterate Through Arrays and Array-like Objects in JavaScript?

Mary-Kate Olsen
Release: 2024-12-23 13:44:33
Original
460 people have browsed it

How Can I Efficiently Iterate Through Arrays and Array-like Objects in JavaScript?

Looping Through Arrays in JavaScript

In JavaScript, there are various ways to iterate through the elements of an array:

Looping Over Genuine Arrays

  • For-of Loop (ES2015 ):
for (const element of theArray) {
    // Use `element`...
}
Copy after login
  • forEach (ES5 ):
theArray.forEach(element => {
    // Use `element`...
});
Copy after login
  • Simple For Loop:
for (let index = 0; index < theArray.length; ++index) {
    const element = theArray[index];
    // Use `element`...
}
Copy after login
  • For-in (with Safeguards):
for (const propertyName in theArray) {
    if (/*...is an array element property (see below)...*/) {
        const element = theArray[propertyName];
        // Use `element`...
    }
}
Copy after login

Looping Over Array-like Objects

  • For-of Loop (ES2015 ):
for (const element of arrayLike) {
    // Use `element`...
}
Copy after login
  • forEach (ES5 ):
arrayLike.forEach(element => {
    // Use `element`...
});
Copy after login
  • Simple For Loop (with Caution):
for (let index = 0; index < arrayLike.length; ++index) {
    // Note: `arrayLike.length` may not be reliable.
    if (arrayLike.hasOwnProperty(index)) {
        const element = arrayLike[index];
        // Use `element`...
    }
}
Copy after login
  • Array.from and For-of Loop:
const arrayLikeItems = Array.from(arrayLike);
for (const element of arrayLikeItems) {
    // Use `element`...
}
Copy after login

Recommendations

  • For genuine arrays, use the for-of loop or forEach if your callback is a simple synchronous function.
  • For array-like objects, use the for-of loop with caution, and consider using Array.from() to create a genuine array first for greater reliability.

The above is the detailed content of How Can I Efficiently Iterate Through Arrays and Array-like Objects 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