所以我有一个包含3个分数的脚本,我希望代码能够找到最高分,并根据哪个变量得分最高来打印一条消息。我知道Math.max()
找到了最大值,但我希望它找到具有最大值的变量名。我该怎么做?
答案 0 :(得分: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 :(得分: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!
}
答案 2 :(得分: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];
答案 3 :(得分: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'