"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What are the Different Ways to Loop Through a JavaScript Array?

What are the Different Ways to Loop Through a JavaScript Array?

Published on 2024-12-26
Browse:107

What are the Different Ways to Loop Through a JavaScript Array?

Looping Through an Array Using JavaScript

Iterating through the elements of an array is a common task in JavaScript. There are several approaches available, each with its own strengths and limitations. Let's explore these options:

Arrays

1. for-of Loop (ES2015 )

This loop iterates over the values of an array using an iterator:

const arr = ["a", "b", "c"];
for (const element of arr) {
  console.log(element); // "a", "b", "c"
}

2. forEach

forEach is a method that iterates over the array and calls a function for each element:

arr.forEach(element => {
  console.log(element); // "a", "b", "c"
});

3. Simple for Loop

This loop uses a counter variable to iterate over the array elements:

for (let i = 0; i 

4. for-in Loop (with Safeguards)

for-in iterates over an array's properties, which include its elements. However, it's important to use safeguards to avoid iterating over prototype properties:

for (const property in arr) {
  // Check if 'property' is an array element property
  if (arr.hasOwnProperty(property)) {
    console.log(arr[property]); // "a", "b", "c"
  }
}

5. Iterator (ES2015 )

Arrays are iterable objects and provide an iterator that can be manually advanced using next():

const iterator = arr[Symbol.iterator]();
while (true) {
  const result = iterator.next();
  if (result.done) break;
  console.log(result.value); // "a", "b", "c"
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3