Javascript正在查找最大值

Javascript finding the Maximum

本文关键字:最大值 查找 Javascript      更新时间:2023-09-26

所以我有一个3分的脚本,我希望代码找到最高分,并根据哪个变量是最高分打印一条消息。我知道Math.max()找到最大值,但我希望它找到具有最大值的变量名。我该怎么做?

您可以执行以下

var score1 = 42;
var score2 = 13;
var score3 = 22;
var max = Math.max(score1, score2, score3);
if (max === score1) {
  // Then score1 has the max
} else if (max === score2) {
  // Then score2 has the max
} else {
  // Then score3 has the max 
}

如果你只想比较这三者,就不要用Math.max了。

您只想检查一个值是否高于其他两个值:

var a = 5;
var b = 22;
var c = 37;
if (a > b && a > c) {
  // print hooray for a!
} else if (b > a && b > c) {
  // print hooray for b!
} else if (c > b && c > a) {
  // print hooray for c!
}

您可以使用数组,对数组进行排序,然后取第一个位置。

   var score1 = 42;
    var score2 = 13;
    var score3 = 22;
    var a=[score1,score2,score3];
    function sortNumber(a,b){return b - a;}
    var arrayMax=a.sort(sortNumber)[0];

http://jsfiddle.net/GKaGt/6/

您可以将值保存在对象中,循环并找到最大值。

var scores = {score1: 42, score2: 13, score3: 22},
maxKey = '', maxVal = 0;
for(var key in scores){
   if(scores.hasOwnProperty(key) && scores[key] > maxVal){
      maxKey = key;
      maxVal = scores[key];
   }
}
alert(maxKey); // 'score1'