javascript each code example
Example 1: jquery each
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
Example 2: javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
Example 3: javascript foreach
var colors = ['red', 'blue', 'green'];
colors.forEach(function(color) {
console.log(color);
});
Example 4: for each js
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
fruits.forEach(function(fruit){
console.log('I want to eat a ' + fruit)
});
Example 5: 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 6: foreach javascript
let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
console.log(word);
});