Looping Through Arrays in JavaScript
In Java, you can employ a for loop to iterate over the elements within an array. Similar functionality is available in JavaScript with three primary options:
Sequential for loop:
This classic for loop provides control over the iteration process, allowing you to specify loop initialization, condition, and increment.
var myStringArray = ["Hello", "World"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { console.log(myStringArray[i]); }
forEach:
The forEach method offers a concise and functional approach, applying a callback function to each element in the array.
myStringArray.forEach((x, i) => console.log(x));
for-of loop:
Introduced in ES6, the for-of loop iterates over the values in an array in a concise manner.
for (const x of myStringArray) { console.log(x); }
The above is the detailed content of How Can I Iterate Through JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!