javascript array foreach example
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
javascript array foreach example
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
For-each over an array in JavaScript
/** 1. Use forEach and related */
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
/** 2. Use a simple for loop */
var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
console.log(a[index]);
}
/**3. Use for-in correctly*/
// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
if (a.hasOwnProperty(key) && // These checks are
/^0$|^[1-9]\d*$/.test(key) && // explained
key <= 4294967294 // below
) {
console.log(a[key]);
}
}
/** 4. Use for-of (use an iterator implicitly) (ES2015+) */
const a = ["a", "b", "c"];
for (const val of a) {
console.log(val);
}
/** 5. Use an iterator explicitly (ES2015+) */
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
console.log(entry.value);
}
for each js
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits below
// Normal way
fruits.forEach(function(fruit){
console.log('I want to eat a ' + fruit)
});
js foreach
var stringArray = ["first", "second"];
myArray.forEach((string, index) => {
var msg = "The string: " + string + " is in index of " + index;
console.log(msg);
// Output:
// The string: first is in index of 0
// The string: second is in index of 1
});
array.foreach
const arr = [0, 3, "hola", "hello", ";", true, [3, 6, 1]];
arr.forEach((element, index) => {
console.log(element, index);
});
//output:
// 0 0
// 3 1
// hola 2
// hello 3
// ; 4
// true 5
// [3, 6, 1] 6
javascript array for each
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us