There are many way to loop JavaScript array, some of them are -
- for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
- xs.forEach((x, i) => console.log(x));
- for (const x of xs) { console.log(x); }
We explain in details bellow -
Source: Stack Overflow
Sequential for loop:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}
Source: Stack Overflow
forEach:
const array = ["one", "two", "three"]
array.forEach(function (item, index) {
console.log(item, index);
});
Source: Stack Overflow
ES6 for of statement:
let colors = ['red', 'green', 'blue'];
for (const color of colors){
console.log(color);
}
Tags
javascript