2012-02-16 57 views
0

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

+0

除非将值存储在对象中,否则无法从其值中获取变量的名称。 – 2012-02-16 17:50:48

回答

2

你可以做以下

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 
} 
1

不要打扰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! 
} 
1

你可以使用一个数组,数组排序,然后在第一个位置。

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/

+0

他想要变量的名称,而不是值。 – 2012-02-16 17:45:14

1

你可以保持在一个对象,遍历你的价值观,并找到最大。

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'