Home  >  Article  >  Web Front-end  >  How to sum and average javascript arrays

How to sum and average javascript arrays

青灯夜游
青灯夜游Original
2022-03-08 17:44:034961browse

Method: 1. Use the "for(i=0;i

How to sum and average javascript arrays

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(&#39;数组的和为&#39;+getSum(arr)+&#39;\n&#39;+&#39;数组的平均值为&#39;+getAve(arr));

How to sum and average javascript arrays

[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!

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
Previous article:What are es6 and es7Next article:What are es6 and es7