Home >Web Front-end >JS Tutorial >How Do I Iterate Through JavaScript Arrays Using Different Looping Methods?

How Do I Iterate Through JavaScript Arrays Using Different Looping Methods?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 19:06:14485browse

How Do I Iterate Through JavaScript Arrays Using Different Looping Methods?

Looping Through Arrays in JavaScript

Just like in Java, you can utilize a for loop to iterate through the elements in an array in JavaScript.

Looping Options:

There are three primary options for looping through an array in JavaScript:

  1. Sequential for loop:

    • Syntax: for (var i = 0; i < array.length; i ) { ... }
    • Example:

      var myStringArray = ["Hello", "World"];
      var arrayLength = myStringArray.length;
      for (var i = 0; i < arrayLength; i++) {
          console.log(myStringArray[i]); // Outputs: Hello, World
      }
  2. forEach loop:

    • Syntax: array.forEach((element, index) => {...})
    • Example:

      myStringArray.forEach((x, i) => console.log(x)); // Outputs: Hello, World
  3. for...of loop:

    • Syntax: for (const element of array) { ... }
    • Example:

      for (const x of myStringArray) {
          console.log(x); // Outputs: Hello, World
      }

The above is the detailed content of How Do I Iterate Through JavaScript Arrays Using Different Looping Methods?. 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