Home > Article > Web Front-end > How to find the maximum value of an array in javascript
Javascript method to find the maximum value of an array: 1. Declare a variable max that holds the largest element; 2. Traverse the array and compare each array element inside with max; 3. When the array element is greater than max, Store the array elements in max; 4. Output max.
The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer
How to find the maximum value of an array with javascript?
JavaScript finds the maximum value of the elements in the array
Find the maximum value in the array [2,6,1,77,52,25,7] maximum value.
Declare a variable max that holds the largest element
The default maximum value max is defined as The first element in the array arr[0]
Traverse the array and compare each array element with max
If If this array element is greater than max, store this array element in max, otherwise continue to the next round of comparison
Finally output this max
var arr = [2, 6, 1, 77, 52, 25, 7, 99]; var max = arr[0]; for (var i = 1; i < arr.length; i++) { if (max < arr[i]) { max = arr[i]; } } console.log(max);
99
// 利用函数求数组 [3, 77, 44, 99, 143] 中的最大数值。 function getArrMax(arr) { // arr 接受一个数组 arr = [3, 77, 44, 99, 143] var max = arr[0]; for (var i = 1; i < arr.length; i++) { if (max < arr[i]) { max = arr[i]; } } return max; } // getArrMax([3, 77, 44, 99, 143]); // 实参是一个数组送过去 var re = getArrMax([3, 77, 44, 99, 143]); console.log(re);
143
function getMax() { var max = arguments[0]; for (var i = 1; i < arguments.length; i++) { if (max < arguments[i]) { max = arguments[i]; } } return max; } console.log(getMax(1, 2, 3)); console.log(getMax(1, 2, 3, 4, 5)); console.log(getMax(11, 2, 34, 444, 5, 100));
3
5
444
Recommended learning: "javascript basic tutorial"
The above is the detailed content of How to find the maximum value of an array in javascript. For more information, please follow other related articles on the PHP Chinese website!