所以我有一个3分的脚本,我希望代码找到最高分并根据哪个变量是最高分打印出一条消息。我知道Math.max()
找到最大值,但我希望它找到具有最大值的变量名称。我该怎么做呢?Javascript找到最大值
0
A
回答
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];
+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'
相关问题
- 1. 在数组中找到最大值并在javascript中找到最大值
- 2. 如何找到最大值?
- 3. 找到R中每行最大最大值和第二大最大值R
- 4. Javascript:使用reduce()查找最小值和最大值?
- 5. 的Javascript $ .MAP()Math.Max.Appy()找到最大高度
- 6. 如何找到对象的最大值和最小值的文字由JavaScript
- 7. Javascript最大值的数组,并找到它在哪里?
- 8. For循环未找到数组的最大值(Javascript)
- 9. 找到[最大值,最小值在列表蟒列表值
- 10. 下划线找到对象值的最小值和最大值
- 11. 找到每行的最大值
- 12. 在阵列中找到的最大值
- 13. 找到子对象的最大值
- 14. XQuery的分组,并找到最大值
- 15. 找到最大值密钥对
- 16. 找到最大值的递归方法
- 17. NSArray中找到最大数值
- 18. 找到两个表格的最大值,
- 19. ROW_NUMBER了分区,找到最大Rn值
- 20. 每天找到单个最大值
- 21. 从csv列中找到最大值
- 22. 从表中找到最大值
- 23. 蜂巢查询找到最大值
- 24. 查找最大值/最小值
- 25. 查找局部最小值/最大值
- 26. 查找最小值和最大值JAVA
- 27. 查找最后最大值/替代最大值为ARRAYFORMULA
- 28. 如何找到标量的最大值和最小值?
- 29. 用数组找到和,最小值,最大值
- 30. 找到最小值和最大值以及R中
除非将值存储在对象中,否则无法从其值中获取变量的名称。 – 2012-02-16 17:50:48