Home > Article > Web Front-end > How to find the maximum value of a number string in javascript
Javascript method to find the maximum value of a digital string: 1. Find the maximum and minimum values of the js array through string splicing; 2. Use the sorting method to find the maximum and minimum values; 3. Find through the hypothesis method Maximum and minimum values; 4. Find the maximum value through the max and min methods of Math.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Four ways to find the maximum and minimum values of js arrays
Given array [54,65,43,21,12,34, 45,58,97,24], find its maximum and minimum values?
Define array
var ary = [54,65,43,21,12,34,45,58,97,24];
1. String splicing method
Use toString and join to convert the array into a string, then splice it with the max and min methods of Math respectively, and finally execute the eval method
var maxN = eval("Math.max(" + ary.toString() + ")"); var minN = eval("Math.min(" + ary.toString() + ")");
or
var maxN = eval("Math.max(" + ary.join() + ")"); var minN = eval("Math.min(" + ary.join() + ")");
2. Sorting method
First sort the array from small to large. The first one in the array is the minimum value, and the last one is is the maximum value
ary.sort(function(a,b){return a-b;}); var minN = ary[0]; var maxN = ary[ary.length-1];
3. Assumption method
Assume that the first one in the array is the maximum (or minimum value), and compare it with the following values. If the latter values are larger than the maximum If the value is larger (or smaller than the minimum value), replace the maximum value (or minimum value)
var maxN = ary[0]; var minN = ary[0]; for(var i=1;i<ary.length;i++){ var cur = ary[i]; cur>maxN ? maxN=cur : null; cur<minN ? minN=cur : null; }
[Recommended learning: js basic tutorial]
4. The max and min methods of Math
Use the apply method to make the array available as a passed parameter
var maxN = Math.max.apply(null,ary); var minN = Math.min.apply(null,ary);
The above is the detailed content of How to find the maximum value of a number string in javascript. For more information, please follow other related articles on the PHP Chinese website!