React - 计算元素之间的较大值仅部分起作用

React - Calculating the bigger value between elements only working partially

我正在比较两个不同的团队以确定哪个更强。 通过计算两队得分的平均值进行比较,数值越大的队伍越强。

我在这里复制了我的案例:DEMO

这些是用到的函数

const getAverage = (league, team) => {
  if (isNaN(league[0][team])) return null;

  return league.map(x => x[team]).reduce((a, c) => a + c) / league.length;
};

const maxAverage = (league, teams) => {
  return teams
    .map(team => {
      return {
        team: team,
        avg: getAverage(league, team)
      };
    })
    .reduce((a, b) => (a.avg > b.avg ? a : b)).team;
};


<p>Stronger Team:{maxAverage(this.state.selectedLeague, [this.state.selectedHomeTeam,this.state.selectedAwayTeam])}</p>

如您在演示中所见,它仅部分起作用。

例如,如果我将 select Atletico 与 Barcelona 进行比较,它定义了 Barcelona 更强,这是错误的(-2 不大于 0),但在另一个绕过 selecting Barcelona against Atletico 它定义了 Atletico 更强,这是正确的(0 大于 -2)。

我的问题出在哪里,我该如何解决?

在您的 maxAverage 函数中,您应该在 scores 对象上引用您想要 select 的确切联赛。

之前,您试图传递整个 scores 对象,该对象由 LigaPremier 数组组成。这就是为什么当您尝试 运行 该方法时它将 return 为空。

相反,您应该将 selected 联赛传递给 getAverage 方法,该方法接受 league 作为数组(不是数组对象)。

这应该是您的 maxAverage 函数所需的更改。

const maxAverage = (league, teams) => {
  return teams
    .map(team => {
      return {
        team: team,
        avg: getAverage(scores[league], team)
      };
    })
    .reduce((a, b) => (a.avg > b.avg ? a : b)).team;
};

我已经在 here 上创建了一个演示。

您错过了 maxAverage 的一步:

 <p>
    Stronger Team:
      {maxAverage(scores[this.state.selectedLeague], [
        this.state.selectedHomeTeam,
        this.state.selectedAwayTeam
       ])}
  </p>

它使用 getAverage 但这需要分数,而不仅仅是球队的名称。尝试使用上面的代码,它似乎有效。

尝试分解代码并调试。我最终将几个 recuder 函数移动到它们自己的函数中(只是为了调试),然后添加一个 "debugger;" 这样我就可以在那个页面上找到 运行 js。

打赌你错过了它:P