javascript取两个数字中的最大值的方法
墨初 Web前端 1589阅读
在js脚本取两个数之间的最大值可以使用Math对象中的max()方法,或三元运算符以及if判断等等。下面73so的小编就详细的说一下。
javascript取两个数最大值的方法
方法1:
js中Math对象中的max()方法可以返回两个数中最高的数字。
例:
// https://www.73so.com console.log(Math.max(5, 10)); console.log(Math.max(10, 8)); console.log(Math.max(8, 2)); console.log(Math.max(2, 3.5)); console.log(Math.max(1, 10));
方法2:
利用js中的三元运算符号来判断两个数的大小,并取最大的数。
例:
// 为了方便调用这里搞成函数
function max(first,second)
{
return first > second ? first : second;
}
console.log(max(2,3));
console.log(max(2,1));
console.log(max(-2,3));方法3:
利用if判断语句来选取两个数中最大的数字。
例:
// 为了方便调用这里搞成函数
function max(first, second) {
if (first > second) {
return first
} else {
return second
};
}
console.log(max(2, 3));
console.log(max(2, 1));
console.log(max(-2, 3));以上就是js中判断两个数大小并取最大数字的方法,各位可以参考一下。