计算数组中对象属性的平均值

时间:2014-09-19 09:21:51

标签: javascript arrays average

我正在尝试计算一周的平均温度,但我不知道我会怎么做。我尝试了一些东西,但最终结果将是'NaN'或'Infinity'。绝对在这里做错了..

以下是我需要使用的代码:

var temperatures;

temperatures = new Array();

temperatures["monday"] = 23.5;
temperatures["tuesday"] = 22.3;
temperatures["wednesday"] = 28.5;
temperatures["thursday"] = 23.5;
temperatures["friday"] = 22.3;
temperatures["saturday"] = 28.5;
temperatures["sunday"] = 29.5;

当阵列像[0],[1]而不是包含日期的字符串时,我得到它的工作,但我不知道如何像上面那样做。此外,如果您有任何建议,请尝试保持代码基本,因为令人惊讶的是,“高级代码”在我的班级中由于某种原因不太受欢迎。

感谢阅读。

4 个答案:

答案 0 :(得分:3)

平均值只是总数除以温度数

var temperatures = {},
    length = 0,
    total  = 0;

temperatures["monday"] = 23.5;
temperatures["tuesday"] = 22.3;
temperatures["wednesday"] = 28.5;
temperatures["thursday"] = 23.5;
temperatures["friday"] = 22.3;
temperatures["saturday"] = 28.5;
temperatures["sunday"] = 29.5;

for (var day in temperatures) {
    total += temperatures[day];
    length++;
}

var average = total / length;

请注意,数组没有命名键,只有对象

答案 1 :(得分:0)

尝试:

 var temperatures;
    var sum = 0,
        count = 0;
    temperatures = new Array();
    
    temperatures["monday"] = 23.5;
    temperatures["tuesday"] = 22.3;
    temperatures["wednesday"] = 28.5;
    temperatures["thursday"] = 23.5;
    temperatures["friday"] = 22.3;
    temperatures["saturday"] = 28.5;
    temperatures["sunday"] = 29.5;
    
    for (var prop in temperatures) {
        if (temperatures.hasOwnProperty(prop)) {
            count++;
            sum += temperatures[prop];
        }
    }

    var average = (sum / count);
    alert(average);

答案 2 :(得分:0)

如果你想要键值对,你应该尝试使用Object而不是Array。

var temperatures;

temperatures = new Object();

temperatures["monday"] = 23.5;
temperatures["tuesday"] = 22.3;
temperatures["wednesday"] = 28.5;
temperatures["thursday"] = 23.5;
temperatures["friday"] = 22.3;
temperatures["saturday"] = 28.5;
temperatures["sunday"] = 29.5;

alert(temperatures["sunday"]);

你将获得键值对js对象, 你可以将它用于平均值:

var sum = 0;
for(key in temperatures)
{
   sum  = sum+temperatures[key];
   console.log(temperatures[key]);
}
alert(sum/7); 

Check this Demo

答案 3 :(得分:0)

我相信穿越会给你带来麻烦。这是解决方案

DEMO

var count=0,total=0;
for(t in temperatures)
{
    total = total+temperatures[t]
    count++;
}
alert(total/count);//average