The best value of the array of JS face questions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.