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
Mary-Kate OlsenOriginal
2024-12-23 13:44:33482browse

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

Looping Over Array-like Objects

  • For-of Loop (ES2015 ):
for (const element of arrayLike) {
    // Use `element`...
}
  • forEach (ES5 ):
arrayLike.forEach(element => {
    // Use `element`...
});
  • 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`...
    }
}
  • Array.from and For-of Loop:
const arrayLikeItems = Array.from(arrayLike);
for (const element of arrayLikeItems) {
    // Use `element`...
}

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!

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