简体   繁体   中英

Javascript - How to compare property values in objects in an array

I am trying to iterate through the games in team. each game records a score for the team and the opponent. I am trying to show how many games the team has won but i am getting NaN returned.

Please help?

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

Initialize won with a value:

 let won = 0;

Otherwise, won is equal to undefined in the beginning.

undefined + 1 will give you NaN .

NaN + 1 will give you NaN again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM