【问题标题】:How can I keep track of array index with for...of loop? [duplicate]如何使用 for...of 循环跟踪数组索引? [复制]
【发布时间】:2021-08-26 06:04:10
【问题描述】:

这是对象:

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,
  },
};

我想使用for..of 并在循环时跟踪数组索引。

可能的解决方案:

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

或者:

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

但是是否可以在 for 语句中声明任何变量并对其进行跟踪?

谢谢。

【问题讨论】:

标签: javascript arrays for-loop


【解决方案1】:

你不能。但是您有以下四种选择:

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

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2013-02-08
    • 2019-12-07
    • 2014-09-19
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多