Home  >  Article  >  Web Front-end  >  How to find the average of es6 array

How to find the average of es6 array

青灯夜游
青灯夜游Original
2022-05-05 15:54:002503browse

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.

How to find the average of es6 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);

How to find the average of es6 array

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);

How to find the average of es6 array

3. Divide the sum of elements by the number of elements to calculate the average

var average=r/len;
console.log("数组平均值为:"+average);

How to find the average of es6 array

[Related recommendations: javascript video tutorialwebfrontend

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn