In programming, processing arrays is a very common operation. Among them, finding the average is also a very basic requirement. In JavaScript, there are multiple ways to achieve this functionality. Below we will introduce several common methods.
The most basic method is to use for loop to traverse the array elements one by one, accumulate them, and finally divide by the length of the array to get the average .
function average(arr) { var sum = 0; for(var i = 0; i < arr.length; i++) { sum += arr[i]; } return sum / arr.length; }
In this function, a sum variable is first defined to store the cumulative result. Then use a for loop to traverse the entire array, adding the value of the current element to sum each time. Finally, divide sum by the length of the array to get the average.
The reduce method is a method that comes with the array prototype object in JavaScript. It receives a callback function and an initial value, and then sequentially Each element and the previous accumulated result are passed into the callback function, and the final result is calculated. Therefore, we can use the reduce method to achieve averaging.
function average(arr) { var sum = arr.reduce(function(prev, cur) { return prev + cur; }, 0); return sum / arr.length; }
In this function, we first use the reduce method to accumulate all the elements in the array, and assign the final result to the sum variable. Then divide sum by the length of the array to get the average.
In ES6, we can use arrow function and Array.prototype.reduce method to implement it more concisely The operation of finding the average.
const average = arr => arr.reduce((prev, cur) => prev + cur, 0) / arr.length;
In this function, we use the arrow function to define the callback function, and use the reduce method to accumulate all the elements in the array, divide the final result by the length of the array, and return it together. Thanks to the syntactic sugar of arrow functions, the code appears very concise.
Summary
The above three methods are all classic methods of finding averages. The method of using for loop is relatively basic and suitable for beginners to understand. Using the reduce method can reduce the amount of code and make the code structure clearer. It is also more suitable for the idea of functional programming. Using ES6 arrow functions and the Array.prototype.reduce method can further simplify the code. In actual development, we can choose one of the methods to implement the averaging operation according to actual needs.
The above is the detailed content of javascript find average. For more information, please follow other related articles on the PHP Chinese website!