how to use foreach loop in javascript code example
Example 1: javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
Example 2: For-each over an array in JavaScript
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
console.log(a[index]);
}
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
if (a.hasOwnProperty(key) &&
/^0$|^[1-9]\d*$/.test(key) &&
key <= 4294967294
) {
console.log(a[key]);
}
}
const a = ["a", "b", "c"];
for (const val of a) {
console.log(val);
}
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
console.log(entry.value);
}
Example 3: es6 forEach
const array1 = ['a', 'b', 'c'];
array1.forEach((element) => {
console.log(element)
});
Example 4: javascript foreach
let numbers = ['one', 'two', 'three', 'four'];
numbers.forEach((num) => {
console.log(num);
});
Example 5: forEach index
const array1 = ['a', 'b', 'c'];
array1.forEach((element, index) => console.log(element, index));
Example 6: how to use the foreach method in javascript
groceries.forEach(groceryItem => console.log(groceryItem));