Home >Web Front-end >Front-end Q&A >How to sum and average javascript arrays
Method: 1. Use the "for(i=0;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript array sum and average
In JavaScript, we can traverse the array to sum, and then divide by the length of the array to get the average number.
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; }
Define an array test:
var arr=[1,2,3,4,5]; var j=arr.length; console.log(arr); console.log('数组的和为'+getSum(arr)+'\n'+'数组的平均值为'+getAve(arr));
[Related recommendations: javascript video tutorial 、web front end】
The above is the detailed content of How to sum and average javascript arrays. For more information, please follow other related articles on the PHP Chinese website!