2012-02-16 77 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'