javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
javascript foreach
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);
}
foreach javascript
let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
console.log(word);
});
// one
// two
// three
// four
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
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