Q:

javascript foreach index

const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})
28
var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
    console.log(color);
});
13
let numbers = ['one', 'two', 'three', 'four'];

numbers.forEach((num) => {
  console.log(num);
});  // one   //two //three // four
8
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));
20
let array = ['Item 1', 'Item 2', 'Item 3'];

array.forEach(item => {
	console.log(item); // Logs each 'Item #'
});
6
users.forEach((user, index)=>{
	console.log(index); // Prints the index at which the loop is currently at
});
5
const iterable = [...];
for (const [index, elem] in iterable.entries()) {
  f(index, elem);
}

// or
iterable.forEach((elem, index) => {
  f(index, elem);
});
1
const arr = [10,20,30,40]

arr.forEach(function(item, index){
    console.log(item, index);
})
3
let colors = ['red', 'blue', 'green'];
// idx and sourceArr optional; sourceArr == colors
colors.forEach(function(color, idx, sourceArr) {
	console.log(color, idx, sourceArr)
});
// Output:
// red 0 ['red', 'blue', 'green']
// blue 1 ['red', 'blue', 'green']
// green 2 ['red', 'blue', 'green']
7
let names = ['josh', 'joe', 'ben', 'dylan'];
// index and sourceArr are optional, sourceArr == ['josh', 'joe', 'ben', 'dylan']
names.forEach((name, index, sourceArr) => {
	console.log(color, idx, sourceArr)
});

// josh 0 ['josh', 'joe', 'ben', 'dylan']
// joe 1 ['josh', 'joe', 'ben', 'dylan']
// ben 2 ['josh', 'joe', 'ben', 'dylan']
// dylan 3 ['josh', 'joe', 'ben', 'dylan']
8

New to Communities?

Join the community