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);
}
for each javascript
let numbers = ['one', 'two', 'three', 'four'];
numbers.forEach((num) => {
console.log(num);
}); // one //two //three // four
for each array javascript
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(getArrayValues);
function getArrayValues(item, index) {
console.log( index + ":" + item);
}
/*
result:
0:apple
1:orange
2:cherry
*/
javascript for each
const emperors = [{
name: 'D. Luffy',
age: 10
},{
name: 'Jhey',
age: 30
}];
emperors.forEach(emperor => console.log(`${emperor.name} is ${emperor.age} years old `));
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