简体   繁体   English

Javascript - 如何比较数组中对象的属性值

[英]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.我试图展示球队赢了多少场比赛,但我得到了 NaN 的回报。

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:用一个值初始化won

 let won = 0;

Otherwise, won is equal to undefined in the beginning.否则, won就等于undefined

undefined + 1 will give you NaN . undefined + 1 会给你NaN

NaN + 1 will give you NaN again. NaN + 1 将再次给你NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何比较数组中的值,即对象数组中的值与对象的属性? - How to compare values in an array, that is inside an array of objects, with a property of the objects? 如何比较和计算放在javascript数组中的几个对象的属性值的实例? - How to compare and count instances of several objects' property values placed in array in javascript? 比较来自不同对象的数组属性值 - Compare array property values from different objects Javascript - 比较两个数组对象和 append 值 - Javascript - Compare two array objects and append values 如何在javascript中比较数组1[对象数组]与数组2 - How to compare array 1[array of objects] with array 2 in javascript 如何在 JavaScript 的 2 个对象数组中检查相等的属性值? - How to check for equal property values in 2 Array of Objects in JavaScript? Javascript 如何从对象数组中获取属性的所有值? - Javascript How to get all values for a property from an Array of Objects? 如何比较数组的多个对象中的属性值? - How to compare a property value in multiple objects of an array? 通过属性比较对象数组,然后 append 数组中的新 object:Javascript - Compare array of objects by a property and then append the new object inside the array: Javascript 访问对象数组javascript中的对象属性值 - Access object property values in an array of objects javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM