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);
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);
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])
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));//最小值
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));//最小值