簡體   English   中英

在數組中獲取最高和最低值的最有效方法是什么

[英]What is the most efficient way to get the highest and the lowest values in a Array

javascript中是否有類似PHP: max()東西?

可以說我有一個像這樣的數組:

[2, 3, 23, 2, 2345, 4, 86, 8, 231, 75]

我想返回此數組中的最高和最低值。 最快的方法是什么?

我努力了:

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

有沒有更簡單的方法來檢索數組的最大值和最小值?

應用 Math.maxMath.min內置方法可以非常快:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM