Looping Through an Array in JavaScript
JavaScript arrays offer multiple ways to iterate through their elements. Among these methods are the for-of loop, forEach, the traditional for loop, the for-in loop with proper safeguards, and iterators.
Genuine Arrays
For-of Loop (ES2015 ):
Iterates over elements of an array directly using an implicit iterator, making it the simplest and async-friendly option:
for (const element of theArray) { // ...use `element`... }
forEach (ES5 ):
A callback-based method for iterating over array elements. While not async-friendly, it has family methods like some and every that can be useful:
theArray.forEach(element => { // ...use `element`... });
For Loop:
A classic looping structure for traversing arrays, providing async-friendliness:
for (let index = 0; index < theArray.length; ++index) { const element = theArray[index]; // ...use `element`... }
For-in Loop (With Safeguards):
Iterates over both array indices (not elements) and any non-inherited, non-symbol property names of the array object itself, which can cause unexpected behavior. Use with caution:
for (const propertyName in theArray) { if (/^\d+$/.test(propertyName)) { const element = theArray[propertyName]; // ...use `element`... } }
Explicit Iterator (ES2015 ):
Utilizes the Symbol.iterator interface to explicitly create an iterator. However, this method is less commonly used:
const iterator = theArray[Symbol.iterator](); while (true) { const result = iterator.next(); if (result.done) break; const element = result.value; // ...use `element`... }
Array-Like Objects
Iterating over array-like objects requires consideration of their non-array nature, such as the arguments object or Node.js's arguments object. These do not have an iterator property, so specific iteration techniques may be required depending on the object.
The above is the detailed content of How Many Ways Are There to Loop Through a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!