Method: 1. Store the number to be averaged into an array; 2. Use the "for(i=0;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
If you want to find the average of multiple numbers, you need to add the multiple numbers to find the sum, and then divide the sum by the number. So how do you find the average value when you don’t know the specific number of values?
In JavaScript, we can use an array to traverse the array, sum it, and then divide it by the length of the array.
Implementation code:
//数组求元素之和 function getSum(arr) { var sum=0,ave=0,i=0; for(i=0;i<arr.length;i++) { sum+=arr[i]; } return sum; } //求平均分 function getAve(arr) { var sum=0,ave=0,i=0; for(i=0;i<arr.length;i++) { sum+=arr[i]; } ave=sum/arr.length; return ave; } //计算结果 var arr=[1,2,3,4,5]; var j=arr.length; console.log('这'+j+'个数字为'+arr+'\n'+'这些数字的和为'+getSum(arr)+'\n'+'这些数字的平均值为'+getAve(arr));
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to find the average of multiple numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!