计算数组中对象属性的平均值 [英] Calculating the average of object properties in array
问题描述
我正在尝试计算一个星期的平均温度,但是我不太清楚该怎么做.我已经尝试了一些方法,但最终结果将是"NaN"或"Infinity".肯定在这里做错了.
I'm trying to calculate the average temperature of one week, but I do not quite know how I would do this. I've tried out some things but the end result would be either 'NaN' or 'Infinity'. Definitely doing something wrong here..
这是我需要使用的代码:
Here's the code I need to work with:
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]而不是包含日期的字符串时,我得到了它的工作,但是我不知道如何像上面那样做.另外,如果您有任何建议,请尝试使代码保持基本状态,因为出于某种原因,我的课堂上不太喜欢高级代码".
I got it working when the arrays were like [0], [1] instead of Strings containing the days, but I don't know how to do it like above. Also if you have any suggestions please try to keep the code basic as surprisingly enough 'advanced code' isn't too appreciated in my class for some reason.
感谢阅读.
推荐答案
平均值就是总数除以温度数
The average is just the total divided by number of temperatures
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;
请注意,数组没有命名键,只有对象有
Note that arrays don't have named keys, only objects do
这篇关于计算数组中对象属性的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!