Home > Web Front-end > Front-end Q&A > How to sum and average javascript arrays

How to sum and average javascript arrays

青灯夜游
Release: 2022-03-08 17:44:03
Original
5083 people have browsed it

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;
}
Copy after login

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));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template