Home >Web Front-end >Front-end Q&A >How to find the average of es6 array
Method: 1. Use the "arr.reduce(function(p,c){return p c;})" statement to calculate the sum of all elements in the array; 2. Use the "arr.length" statement, Calculate the number of array elements; 3. Use the "elements and/number of elements" statement to calculate the average of the array.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 method of averaging arrays
1. Use the reduce() function to calculate the sum of all elements in the array
var arr = [1,2,3,4,5,6,7,8,9,10]; console.log(arr); var r = arr.reduce(function(pre, curr) { return pre + curr; }); console.log("数组元素之和为:"+r);
2. Use the length attribute to get the number of elements in the array, that is, the length of the array
var len=arr.length; console.log("数组元素个数为:"+len);
3. Divide the sum of elements by the number of elements to calculate the average
var average=r/len; console.log("数组平均值为:"+average);
[Related recommendations: javascript video tutorial、webfrontend】
The above is the detailed content of How to find the average of es6 array. For more information, please follow other related articles on the PHP Chinese website!