2012-02-16 15 views
0

私は3つのスコアを持つスクリプトを持っています。最高のスコアを見つけて、どの変数が最高のスコアであるかに基づいてメッセージを出力します。私はMath.max()が最大値を見つけることを知っていますが、最大値を持つ変数名を見つけたいと思います。私はこれをどのようにして行うのですか?Javascriptが最大値を見つける

+0

オブジェクトに値を格納しない限り、値から変数の名前を取得する方法はありません。 –

答えて

2

あなたはわずか3を比較したい場合は、次の

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

彼は値ではなく変数の名前を求めています。 –

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' 
関連する問題