Home > Web Front-end > JS Tutorial > Summary of methods to find the maximum value in an array using javascript_javascript skills

Summary of methods to find the maximum value in an array using javascript_javascript skills

WBOY
Release: 2016-05-16 15:15:48
Original
1321 people have browsed it

Method 1 (using recursive function):

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);

Copy after login

Method 2 (use for loop to traverse):

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);

Copy after login

Method three (use apply to pass the array into the max method and return it directly):

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

Note: In addition, there are many array sorting methods, all of which can obtain the maximum/minimum value based on the new array index value after sorting.

var a=[1,2,3,5];
alert(Math.max.apply(null, a));//最大值
alert(Math.min.apply(null, a));//最小值

Copy after login

Multidimensional arrays can be modified like this:

var a=[1,2,3,[5,6],[1,4,8]];
var ta=a.join(",").split(",");//转化为一维数组
alert(Math.max.apply(null,ta));//最大值
alert(Math.min.apply(null,ta));//最小值
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template