how to loop through array javascript code example
Example 1: javascript loop through array
var data = [1, 2, 3, 4, 5, 6];
for(let i=0; i<=data.length; i++) {
console.log(data[i])
}
for(let i of data) {
console.log(i)
}
for(let i in data) {
console.log(i)
console.log(data[i])
}
data.forEach((i) => {
console.log(i)
})
data.map((i) => {
console.log(i)
})
Example 2: javascript code to loop through array
var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Example 3: javascript iterate array
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(function(value, index, array) {
txt = txt + value + "<br>";
});
Example 4: javascript loop through array
var colors = ["red","blue","green"];
colors.forEach(function(color) {
console.log(color);
});
Example 5: javascript loop through array
let my_array = [1, 2, 3, 4, 5];
for(let i = 0; i < my_array.length; i++) {
console.log(my_array[i])
}
for(let i of my_array) {
console.log(i)
}
Example 6: loop over an array
let fruits = ['Apple', 'Banana'];
fruits.forEach(function(item, index, array) {
console.log(item, index);
});