简体   繁体   中英

Finding the average of an array without hardcoding in JavaScript

I have to find the average score of:

scores = [85, 93, 65, 65, 92, 81, 93];

While I've been taught how to tackle this problem, I was told to do it without hardcoding which is somewhat of a problem to me because I'm a complete beginner. The hint was to use Math.random() which I already tried using.

let scores = [85, 93, 65, 65, 92, 81, 93];
let randDecimal = Math.random();
let randNum = randDecimal * scores.length;
let randIndex = Math.floor(randNum);
randScore = scores[randIndex];
let averageAddition = randScore * scores.length;
let averageLength = scores.length;
let averageScore = averageAddition / averageLength;
console.log("Average:", averageScore);

This prints different numbers which aren't average of scores I tried hard coding it and got a value of 82, now I can't seem to get 82 again.

Math.random() returns a random number between 0 and 1. It doesn't do you any good at all when trying to calculate the average of an array.

Your previous attempt was not working because instead of calculating the average of an array, it was instead getting a random item from the array.

let scores = [85, 93, 65, 65, 92, 81, 93];
let randDecimal = Math.random(); //random number from 0-1
let randNum = randDecimal * scores.length;
let randIndex = Math.floor(randNum); //random index
randScore = scores[randIndex]; //get item at random index
let averageAddition = randScore * scores.length; 
let averageLength = scores.length;
let averageScore = averageAddition / averageLength; //cancels out previous operation at line 6
console.log("Average:", averageScore);

To calculate the average, you can loop through the array and sum the values in a variable, then divide the sum with the length to find the average.

 let scores = [85, 93, 65, 65, 92, 81, 93]; var sum = 0; scores.forEach(e => sum += e); const avg = sum / scores.length; console.log(avg);

You can make it shorter with Array.reduce() :

 let scores = [85, 93, 65, 65, 92, 81, 93]; const avg = scores.reduce((a, b) => a + b, 0) / scores.length; console.log(avg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM