【问题标题】:Javascript - How to compare property values in objects in an arrayJavascript - 如何比较数组中对象的属性值
【发布时间】:2021-09-09 02:45:29
【问题描述】:

我正在尝试迭代团队中的游戏。每场比赛记录球队和对手的得分。 我试图显示球队赢了多少场比赛,但我返回的是 NaN。

请帮忙?

const team = {
  _games: [{
    opponent: 'Banks',
    teamGoals: 5,
    opponentGoals: 3
  },
  {
    opponent: 'Gales',
    teamGoals: 0,
    opponentGoals: 4
  },
  {
    opponent: 'Ingles',
    teamGoals: 6,
    opponentGoals: 0
  }],
  get games() {
    return this._games;
  },

  addGame(opponent, teamGoals, opponentGoals) {
    const newGame = {
      opponent,
      teamGoals,
      opponentGoals,
    };
    this._games.push(newGame);
  },

};

team.addGame('Frankies', '3', '2');
team.addGame('Chippenham', '2', '4');
team.addGame('Gores', '6', '2');

const numberOfGames = team.games.length;

const gamesWon = () => {
  let won;
  for (let x in team.games){
    if(team.games[x].teamGoals > team.games[x].opponentGoals) {
      won += 1;
    };
  };
  console.log(`Team has won ${won} games`)
};

gamesWon();
console.log(`Team has played: ${numberOfGames} games`)

【问题讨论】:

    标签: javascript for-loop if-statement


    【解决方案1】:

    用一个值初始化won

     let won = 0;
    

    否则,won 开头就等于undefined

    undefined + 1 会给你NaN(非数字)。

    NaN + 1 将再次给你NaN

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多