减少不提供预期总和的功能

时间:2016-03-10 23:07:38

标签: javascript

我有以下代码

var result_goals_against = [];
memo_goals.reduce(function(res, value) {
  if (!res[value.player_id]) {
    res[value.player_id] = {
      goals_against: 0,
      player_id: value.player_id
    };
    result_goals_against.push(res[value.player_id])
  }
  res[value.player_id].goals_against += value.goals_against;
  return res;
}, {});

这是输出:

Most results are NaN and some have undefined appended a couple of times

我担心:行的实际值应该是(1.row = 10),(6.row = 2)和(其余为0),脚本应该总结,但它似乎只是链接值。我尝试将+= value.goals_against;修改为+= +value.goals_against;,因为我在mongodb中的值是字符串而不是数字。

  

示例备忘录数据数组

memo_goals = 
[
{
        "_id" : "Qzg3P8RGakoT3WvRC",
        "match_id" : "f3YWd2WKKz9dCW4CH",
        "team_id" : "2PKzW3Yb27vMqfDYh",
        "player_number" : "7",
        "player_id" : "8KnyCJ3KiqBYmAQ26",
        "saves" : "12",
        "goals_against" : "2"
},
{
        "_id" : "b39KhqCXRFDGccpdW",
        "match_id" : "9bKWj27hF5P87Ags4",
        "team_id" : "2PKzW3Yb27vMqfDYh",
        "player_number" : "7",
        "player_id" : "8KnyCJ3KiqBYmAQ26",
        "saves" : "16"
}
];

1 个答案:

答案 0 :(得分:0)

据我所知,你有两个问题:

  1. 如果value.goals_against是一个字符串(而不是您所说的数字),那么将数字res[value.player_id].goals_against添加到字符串value.goals_against将为您提供字符串,而不是数字。在添加之前,您需要将value.goals_against解析为数字。
  2. value.goals_against显然还包含数据中的undefined值。您需要验证该案例并在添加中将其解析为0.
  3. 要解决上述两个问题,您可以尝试从以下位置更改第10行:

    res[value.player_id].goals_against += value.goals_against;
    

    ...为:

    res[value.player_id].goals_against += (parseInt(value.goals_against) || 0);