Home  >  Article  >  Web Front-end  >  How to find the average value of a two-dimensional array in javascript

How to find the average value of a two-dimensional array in javascript

青灯夜游
青灯夜游Original
2021-10-19 15:04:255843browse

Method for averaging in JS two-dimensional array: 1. Nested double-layer for loop traverses all elements in the two-dimensional array; 2. In the loop body, use "sum =arr1[i][j ]" statement adds up all array elements; 3. Divide the sum of array elements by the number of array elements to find the average.

How to find the average value of a two-dimensional array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript two-dimensional array average value

If we want to find the average value of a two-dimensional array, we need to first obtain the average value of the two-dimensional array For each element, add them up and divide by the number of elements.

So how to get each element of the two-dimensional array?

When you see this, you will think of a for loop, using array subscripts to get elements. Because it is a two-dimensional array, two levels of for loops must be nested: the first level controls the array row subscripts, and the second level controls the array column subscripts.

ok, let’s take a look at the implementation code:

var sum=0;
var B=0; //此变量的定义是为了记录数组内的元素总个数
var arr=[
[12,13,14,15],
[16,17,18,19],
[20,21,22,23]
];
for (var i=0;i<arr.length; i++) // arr1.length是数组行个数
{
for (var j=0;j<arr[i].length;j++) // arr1[i].length是数组列个数
{
sum+=arr[i][j];
B++;
}
}
document.write("平均值为:"+sum/B);

Output results:

How to find the average value of a two-dimensional array in javascript

[Recommended learning: JavaScript advanced tutorial

The above is the detailed content of How to find the average value of a two-dimensional array in javascript. 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