Javascript正在查找最大值
Javascript finding the Maximum
所以我有一个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'
相关文章:
- 在Javascript数组中查找绝对最大值
- 使用函数从数组中查找最小值和最大值
- 正在查找对象集合的最大值
- 在JavaScript多维数组中查找每个x值的最大值
- 在稀疏 JavaScript 数组中查找最大值
- 在带有对象的数组中查找最小值、最大值
- 使用 JavaScript 函数在数组中查找最大值
- 查找局部最大值
- 用于从数组中查找最大值的javascript代码
- 在“跨记录”中查找XML属性的最大值
- 从一个数组中查找一个属性的最大值,并将其传递给新数组
- Javascript正在查找最大值
- 在javascript数组中查找最小-最大值
- 递归地查找数组中的最大值
- 查找子对象的最大值
- Javascript数组查找最大值
- jQuery/JavaScript查找表列中的最大值
- 在数组的数组中查找最大值
- 查找具有最大值的父对象
- 查找幂集的加权子集和的最大值