如何使用javascript获取两个变量的最高值

How can I use javascript to get the highest value of two variables

本文关键字:两个 变量 最高值 何使用 javascript 获取      更新时间:2023-09-26

我有两个变量名称var h1var h2每个都有一些数字。我想获得另一个变量的最高值

尝试此操作以获得最大值:

var result = Math.max(h1,h2)
var highestNum = h1 > h2 ? h1: h2;

或者如果你不喜欢三级陈述:

var highestNum;
if (h1 > h2) { 
    highestNum = h1;
} else {
    highestNum = h2;
}

编辑:有趣的是,if-else语句的运行速度似乎比Math.max(在Chrome 21上)快得多

http://jsperf.com/jbabey-math-max

h1>h2?h1:h2

为什么需要jQuery?

奇特的方式唯一应该做的方式

var otherVar = Math.max(h1,h2);

长途:

var otherVar=0;
if(h1 >= h2)
{
    otherVar = h1;
}
else
{
    otherVar = h2;
}

只有Javascript,没有jQuery。