计算数组中点的平均值 - Javascript

时间:2013-08-28 22:45:09

标签: javascript arrays

我有一个关于一群人的信息的数组:姓名,当前状态,新点,最后事件点

示例:

var group = new Array();
group[0] = "John Doe,beginer,14,7";
group[1] = "Lois Lane,advanced,13,9";
group[2] = "Bruce Waine,advanced,17,10";

我需要一个计算新点平均值的函数。

对于前一个例子,平均值为(14 + 13 + 17)/ 3 = 14.66666666666667

4 个答案:

答案 0 :(得分:2)

如果将数组中的数据从字符串转换为对象,那将会更加容易。这将以两种方式使您受益:1)代码将更易读,易懂,更易于维护,以及2)你不需要做一堆字符串体操来取出相关数据。

做这样的事情:

var group = [
  { name: 'John Doe', status: 'beginner', newPoints: 14, eventPoints: 7 },
  { name: 'Lois Lane', status: 'advanced', newPoints: 13, eventPoints: 9 },
  { name: 'Bruce Waine', status: 'advanced', newPoints: 17, eventPoints: 10 }
];

function getAverageNewPoints(people) {
  var count = people.length || 0,
      average = 0;

  for (var i = 0; i < count; i++) {
    average += people[i].newPoints;
  }

  return average / count;
}

alert('The average of new points in the group is: ' + getAverageNewPoints(group));

答案 1 :(得分:1)

尝试以下方法:

function groupAverage(group) {
    var sum = 0;
    var count = group.length;

    for (var i in group) {
        sum += parseInt(group[i].split(',')[2], 10);
    }

    return sum / count;
}

答案 2 :(得分:1)

将String拆分为,并获取值并将其转换为Number。

var group = new Array();
 group[0] = "John Doe,beginer,14,7";
 group[1] = "Lois Lane,advanced,13,9";
 group[2] = "Bruce Waine,advanced,17,10";
sum=0;

for(var i in group)
{
    sum=sum+Number(group[i].split(",")[2]);

}

console.log(sum/group.length);  

答案 3 :(得分:0)

您的数据结构不正确。您不想使用字符串。您也不应该使用Array构造函数。从:

开始
var group = [
    {name: "John Doe",    rank: "beginner", points: 14, lastScore: 7},
    {name: "Lois Lane",   rank: "advanced", points: 13, lastScore: 9},
    {name: "Bruce Wayne", rank: "advanced", points: 17, lastScore: 10},
],
length = group.length,
sum = 0,
i;

for ( i = 0; i < length; ++i) {
    sum += group[i].points;
}

return sum / length; // Or do something else with the result.
                     // I did no error checking.

您可以使用对象构造函数而不是我使用的内联Object,但这不是必需的。我只是好奇;你是使用字符串作为默认值,还是使用教科书分配的字符串接口部分?

哦,使用[]代替new Array()的一个原因是当你构造Array时,值总是真实的,而[]是假的。

我确实冒昧纠正布鲁斯的姓氏。