Looping Over Arrays in JavaScript
Introduction
JavaScript offers various techniques to iterate through elements in an array. This article explores the available options for traversing arrays and array-like objects.
For Actual Arrays
1. for-of Loop (ES2015 )
The for-of loop iterates over the values of an array using an implicit iterator.
const a = ["a", "b", "c"]; for (const element of a) { console.log(element); // a, b, c }
2. forEach and Related (ES5 )
forEach is a versatile method that calls a callback function for each element of an array. It supports breaking and continuing operations with its related some and every methods.
a.forEach((element) => { console.log(element); // a, b, c });
3. Simple for Loop
This traditional for loop iterates over each index of the array.
for (let i = 0; i < a.length; i++) { const element = a[i]; console.log(element); // a, b, c }
4. for-in Loop (With Caution)
The for-in loop iterates over the properties of an array, including its inherited ones. To avoid unintended behavior, use safeguards to ensure you're only looping through array elements.
for (const propertyName in a) { if (a.hasOwnProperty(propertyName)) { const element = a[propertyName]; console.log(element); // a, b, c } }
5. Iterator (ES2015 )
Explicitly using an iterator provides fine-grained control over the iteration process.
const iter = a[Symbol.iterator](); for (let element of iter) { console.log(element); // a, b, c }
The above is the detailed content of What are the Best Ways to Iterate Over Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!