Home > Article > Web Front-end > How to find the average score in JavaScript
Native JavaScript implementation to find the average score
In front-end development, it is often necessary to find the average of an array of numbers. This function can be easily implemented using JavaScript. Below is a native JavaScript implementation.
function average(arr) { var sum = 0; for (var i = 0; i < arr.length; i++) { sum += arr[i]; } return sum / arr.length; }
This function receives an array of numbers as a parameter, iterates through each element in the array, accumulates the values of all elements and returns the average.
When using this function, you can call it like the following:
var scores = [80, 90, 95, 87, 92]; var avgScore = average(scores); console.log(avgScore); // 输出 88.8
Here, an array containing scores is passed to the function as a parameter. The function returns the average score of the array, and finally outputs the result. to the console.
Use the reduce function to find the average score
In addition to using a loop to traverse the array, we can also use the reduce function in JavaScript to achieve the average score function.
function average(arr) { var sum = arr.reduce(function(a, b) { return a + b; }); return sum / arr.length; }
This function also receives an array of numbers as a parameter, calls the reduce method of the array, accumulates each element in the array, and finally divides it by the length of the array to get the average.
Similarly, the method of using this function is the same as above:
var scores = [80, 90, 95, 87, 92]; var avgScore = average(scores); console.log(avgScore); // 输出 88.8
Summary
In front-end development, averaging is a common operation. JavaScript provides a variety of implementation methods, such as looping through arrays, using reduce functions, etc. When choosing an implementation method, you can choose the most appropriate method according to the situation to improve the readability and maintainability of the code.
The above is the detailed content of How to find the average score in JavaScript. For more information, please follow other related articles on the PHP Chinese website!