所以我有一個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. 在javascript數組中找到最小值最大值
- 3. 如何找到最大值?
- 4. sql - 找到最大值
- 5. 找到最小和最大像素值
- 6. 找到R中每行最大最大值和第二大最大值R
- 7. Javascript:使用reduce()查找最小值和最大值?
- 8. 的Javascript $ .MAP()Math.Max.Appy()找到最大高度
- 9. 找到最大的變數的JavaScript
- 10. 找到最大的整數的JavaScript
- 11. 如何找到對象的最大值和最小值的文字由JavaScript
- 12. 在Javascript數組中找到絕對最大值
- 13. Javascript最大值的數組,並找到它在哪裏?
- 14. For循環未找到數組的最大值(Javascript)
- 15. 如何從JavaScript嵌套數組對象中找到最大值?
- 16. 下劃線找到對象值的最小值和最大值
- 17. 找到[最大值,最小值在列表蟒列表值
- 18. 在列中找到最大值
- 19. 找到一個VB.Net DataTable的最大值
- 20. 如何在表中找到最大值
- 21. 每天找到單個最大值
- 22. 找到隨機數的最大值
- 23. NSArray中找到最大數值
- 24. 從webelement列表中找到最大值
- 25. 找到最大值密鑰對
- 26. 在列表中找到的最大值
- 27. 找到最大值總和三角形
- 28. OpenOffice的計算:找到最大值
- 29. 陰謀圖並找到最大值
- 30. 蜂巢查詢找到最大值
除非將值存儲在對象中,否則無法從其值中獲取變量的名稱。 – 2012-02-16 17:50:48