Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - Calculating the average of object properties in array

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...