Home > Article > Web Front-end > How to find the average value of a two-dimensional array in javascript
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.
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:
[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!