is there something like PHP: max()
in javascript?
lets say i have an array like this:
[2, 3, 23, 2, 2345, 4, 86, 8, 231, 75]
and i want to return the highest and the lowest value in this array. What is the fastest way to do that?
i have tried:
function madmax (arr) {
var max = arr[0],
min = arr[1]
if (min > max) {
max = arr[1]
min = arr[0]
}
for (i=1;i<=arr.length;i++){
if( arr[i] > max ) {
max = arr[i]
}else if( arr[i] < min ) {
min = arr[i]
}
}
return max, min
}
madmax([123, 2, 345, 153, 5, 98, 456, 4323456, 1, 234, 19874, 238, 4])
开发者_StackOverflow社区
Is there a simpler way retrieve the max and min value of a array?
Applying the Math.max
and Math.min
built-in methods can be really fast:
var array = [2, 3, 23, 2, 2345, 4, 86, 8, 231, 75];
var max = Math.max.apply(Math, array); // 2345
var min = Math.min.apply(Math, array); // 2
精彩评论