问题
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;
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.
Thanks for reading.
回答1:
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
回答2:
I believe traversing causing problem for you. here is solution
DEMO
var count=0,total=0;
for(t in temperatures)
{
total = total+temperatures[t]
count++;
}
alert(total/count);//average
回答3:
Try:
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);
回答4:
You should try Object instead of Array, if you wish Key Value pair.
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"]);
you will get key value pair js object, you can use it for Average:
var sum = 0;
for(key in temperatures)
{
sum = sum+temperatures[key];
console.log(temperatures[key]);
}
alert(sum/7);
Check this Demo
来源:https://stackoverflow.com/questions/25930547/calculating-the-average-of-object-properties-in-array