3

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.

2

1 Answer 1

4

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))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.