如何从 1 使用 Object.entries() 方法 JavaScript 开始迭代?

问题描述

const game = {
  team1: 'Bayern Munich',team2: 'Borrussia Dortmund',players: [
    [
      'Neuer','Pavard','Martinez','Alaba','Davies','Kimmich','Goretzka','Coman','Muller','Gnarby','Lewandowski',],[
      'Burki','Schulz','Hummels','Akanji','Hakimi','Weigl','Witsel','Hazard','Brandt','Sancho','Gotze',score: '4:0',scored: ['Lewandowski','Hummels'],date: 'Nov 9th,2037',odds: {
    team1: 1.33,x: 3.25,team2: 6.5,},};

1) 遍历 game.scored 数组并将每个玩家的名字打印到控制台,以及从 1 开始的目标编号,如(目标 1:等)

这是我的第一个解决方案,结果很完美:

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

输出

Goal: 1 Lewandowski

Goal: 2 Gnarby

Goal: 3 Lewandowski

Goal: 4 Hummels

图片结果:

enter image description here

问题是当我使用 Object.entries() 从不同的方法尝试时,迭代不是从 1 开始

灵魂 2

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

输出

Goal: 01 Lewandowski

Goal: 11 Gnarby

Goal: 21 Lewandowski

Goal: 31 Hummels

图片结果:

enter image description here

解决方法

第一种方法获取数组及其条目 (Array#entries),而第二种方法获取对象及其中的条目 (Object.entries)。

对象只有字符串或符号作为键。要将数字作为值,您需要将其转换为数字。最短的方法是取一个 unary plus +

const
    game = { team1: 'Bayern Munich',team2: 'Borrussia Dortmund',players: [['Neuer','Pavard','Martinez','Alaba','Davies','Kimmich','Goretzka','Coman','Muller','Gnarby','Lewandowski'],['Burki','Schulz','Hummels','Akanji','Hakimi','Weigl','Witsel','Hazard','Brandt','Sancho','Gotze']],score: '4:0',scored: ['Lewandowski','Lewandowski','Hummels'],date: 'Nov 9th,2037',odds: { team1: 1.33,x: 3.25,team2: 6.5 } };


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

,

game.scored.entries() 返回一个迭代器对象,其中索引作为数字返回。因此,将 i 的值加 1 会执行加法并给出预期的结果。

Object.entries(game.scored) 以字符串形式返回 key。因此,当您在第二个代码示例中执行 i + 1 时,您的代码执行串联而不是执行加法。由于 i 是字符串,所以 1 将被转换为字符串,然后与 i 的值连接。

要获得所需的结果,请将 i 转换为数字,然后再将其加 1。

有多种方法可以将字符串转换为数字。您可以使用以下方式之一:

  • 使用 + 一元运算符

    for (const [i,v] of Object.entries(game.scored)) 
    {
      console.log(`Goal: ${(+i)+1} ${v}`);
    }
    
  • 使用 parseInt() 函数

    for (const [i,v] of Object.entries(game.scored)) 
    {
      console.log(`Goal: ${parseInt(i) + 1} ${v}`);
    }
    
  • 使用 Number() constructor

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