Example 1: javascript loop through array
var data = [1, 2, 3, 4, 5, 6];
// traditional for loop
for(let i=0; i<=data.length; i++) {
console.log(data[i]) // 1 2 3 4 5 6
}
// using for...of
for(let i of data) {
console.log(i) // 1 2 3 4 5 6
}
// using for...in
for(let i in data) {
console.log(i) // Prints indices for array elements
console.log(data[i]) // 1 2 3 4 5 6
}
// using forEach
data.forEach((i) => {
console.log(i) // 1 2 3 4 5 6
})
// NOTE -> forEach method is about 95% slower than the traditional for loop
// using map
data.map((i) => {
console.log(i) // 1 2 3 4 5 6
})
Example 2: javascript loop through array
var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Example 3: javascript loop through array
var colors = ["red","blue","green"];
colors.forEach(function(color) {
console.log(color);
});
Example 4: javascript loop through array
const myArray = ['foo', 'bar'];
myArray.forEach(x => console.log(x));
//or
for(let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
Example 5: javascript loop through array
var myStringArray = ["hey","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}
Example 6: javascript loop through array
const numbers = [1, 2, 3, 4]
numbers.forEach(number => {
console.log(number);
}
for (let i = 0; i < number.length; i++) {
console.log(numbers[i]);
}
Example 7: javascript loop through array
let array = ['Item 1', 'Item 2', 'Item 3'];
for (let item of array) {
console.log(item);
}
Example 8: javascript loop through array
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}
Example 9: javascript loop through array
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
Example 10: javascript loop through array
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}