JavaScript Implementation Lookup Array maximum method Rollup _javascript tips

Source: Internet
Author: User

Method one (using Recursive functions):

var arr = [9,8,55,66,49,68,109,55,33,6,2,1];
  
var max = arr[0];

function Findmax (i) {
  if (i = = arr.length) return max;
  if (Max < arr[i]) max = arr[i];
  Findmax (i+1);
}
 
Findmax (1);
Console.log (max);

Method two (using for loop traversal):

var arr = [9,8,55,66,49,68,109,55,33,6,2,1];  
var max = arr[0];
for (var i = 1; i < arr.length i++) {
  if (Max < arr[i]) {
    max = arr[i];
  }
}

Console.log (max);

Method Three (use apply to pass the array directly back into the Max method):

Math.max.apply (null,[9,8,55,66,49,68,109,55,33,6,2,1])

Note: In addition, there are many array sorting methods that can be sorted to get the maximum/minimum value based on the new array index value.

var a=[1,2,3,5];
Alert (Math.max.apply (null, a));//maximum
alert (Math.min.apply (null, a));//min value

Multidimensional arrays can be modified like this:

var a=[1,2,3,[5,6],[1,4,8]];
var ta=a.join (","). Split (",");//Convert to one-dimensional array
alert (Math.max.apply (Null,ta));//maximum
alert (NULL, TA));//min value

Related Article

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.