Looping Through Arrays in JavaScript
In JavaScript, there are various ways to iterate through the elements of an array:
Looping Over Genuine Arrays
for (const element of theArray) { // Use `element`... }
theArray.forEach(element => { // Use `element`... });
for (let index = 0; index < theArray.length; ++index) { const element = theArray[index]; // Use `element`... }
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 (const element of arrayLike) { // Use `element`... }
arrayLike.forEach(element => { // Use `element`... });
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`... } }
const arrayLikeItems = Array.from(arrayLike); for (const element of arrayLikeItems) { // Use `element`... }
Recommendations
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!