vendredi 25 juin 2021

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

Aucun commentaire:

Enregistrer un commentaire