Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...