2

This is the object:

const game = {
  team1: 'Bayern Munich',
  team2: 'Borrussia Dortmund',
  players: [
    [
      'Neuer',
      'Pavard',
    ],
    [
      'Burki',
      'Schulz',
    ],
  ],
  score: '4:0',
  scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'],
  date: 'Nov 9th, 2037',
  odds: {
    team1: 1.33,
    x: 3.25,
    team2: 6.5,
  },
};

I want use for..of and keep track of array index while looping.

Possible solution:

for (const [i, player] of game.scored.entries())
  console.log(`Goal ${i + 1}: ${player}`);

Or:

let i = 0
for(const game1 of game.scored) {
  i++;
  console.log(i,game1)
}

But is it possible to declare any variable in for statement and keep track of it?

Thank you.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
Aman Singh
  • 21
  • 1
  • 2

1 Answers1

1

You can't. But you have these four alternatives:

const arr = ['apple', 'banana', 'carrot']

for (const i in arr) { console.log(i, arr[i]) }
for (let i = 0; i < arr.length; i++) { console.log(i, arr[i]) }
for (const [i, elt] of arr.entries()) { console.log(i, elt) }
arr.forEach((elt, i) => console.log(i, elt))
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84