Today continue to share JS common face questions, to find the maximum value of the array, the minimum value, here are listed 4 common solutions, there are other methods can also be achieved, the reader know can be a private messages to me, I will list the comments to the blog, welcome suggestions.
First, sort by array
1 var Arr=[3,4,5,1,2,9,8,7]; 2 var newarr=arr.sort (function (A, b) { 3 return a-B; 4 }) 5 var min=newarr[0]; 6 var max=newarr[arr.length-1 7 8 Console.log (min); 9 console.log (max);
The second, using the Eval method (not recommended, may result in malicious code execution)
1 var arr=[3,4,5,1,2,9,8,7]; 2 var min=eval ("Math.min (" +arr.tostring () + ")"); 3 var max=eval ("Math.max (" +arr.tostring () + ")"); 4 5 console.log (min); 6 Console.log (max);
The third, the hypothesis method (learned C language know)
1 var min=arr[0],max=arr[0]; 2 3 for (var i = 0; i < arr.length; i++) {4 arr[i]>max?max=arr[i]:null;
5 arr[i]<min?min=arr[i]:null; 6 }78console.log (min); 9 Console.log (max);
The fourth kind, skillfully uses apply (old driver solution)
1 var arr=[3,4,5,1,2,9,8,7]; 2 3 var min=math.min.apply (null, arr); 4 var max=math.max.apply (null, arr); 5 6 console.log (min); 7 Console.log (max);
The best value of the array of JS face questions