获取数组中最高和最低值的最有效方法是什么 [英] What is the most efficient way to get the highest and the lowest values in a Array

查看:109
本文介绍了获取数组中最高和最低值的最有效方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有类似PHP的东西: max()在javascript中?

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?

我试过:

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

是否有更简单的方法来检索最大值和数组的最小值?

Is there a simpler way retrieve the max and min value of a array?

推荐答案

应用 Math.max Math.min 内置方法可以非常快:

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

这篇关于获取数组中最高和最低值的最有效方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆