Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

javascript - What is the most efficient way to get the highest and the lowest values in a Array

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...