[英]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.