Q:

forEach index

var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});
11
const iterable = [...];
for (const [index, elem] in iterable.entries()) {
  f(index, elem);
}

// or
iterable.forEach((elem, index) => {
  f(index, elem);
});
1
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
const array1 = ['a', 'b', 'c'];

array1.forEach((element, index) => console.log(element, index));
1
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
const movies = [
{name: "A New Hope", director: "George Lucas", release: "1977-05-25", episodeID: 4},
{name: "Attack of the Clones", director: "George Lucas", release: "2002-05-16", episodeID: 2},
{name: "Return of the Jedi", director: "Richard Marquand", release: "1983-05-25", episodeID: 6},
{name: "Revenge of the Sith", director: "George Lucas", release: "2005-05-19", episodeID: 3},
{name: "The Empire Strikes Back", director: "Irvin Kershner", release: "1980-05-17", episodeID: 5},
{name: "The Phantom Menace", director: "George Lucas", release: "1999-05-19", episodeID: 1}     
]
movies.forEach((movies) => {
  console.log(movies.name);
});
/*A New Hope
Attack of the Clones
Return of the Jedi
Revenge of the Sith
The Empire Strikes Back
The Phantom Menace*/
1
const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
5
let listeDePays = ['France', 'Belgique', 'Japon', 'Maroc'];
listeDePays.forEach(pays => console.log(pays));
0
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
1
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
0

New to Communities?

Join the community