JavaScript求两个数字中最大值的方法:1、利用Math对象的max()方法,语法“Math.max(数字1, 数字2);”;2、利用三元运算符,语法“数字1>数字2 ? 数字1 : 数字2;”。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
JavaScript求两个数字中最大值的方法
1、利用Math对象的max()方法
max() 方法返回具有最高值的数字。
立即学习“Java免费学习笔记(深入)”;
console.log(Math.max(5, 10)); console.log(Math.max(10, 6)); console.log(Math.max(8, -1)); console.log(Math.max(2, 2.5)); console.log(Math.max(10, 10));

2、利用三元运算符
三元运算符(也被称为条件运算符),由一个问号和一个冒号组成,语法格式如下:
条件表达式 ? 表达式1 : 表达式2 ;
如果“条件表达式”的结果为真(true),则执行“表达式1”中的代码,否则就执行“表达式2”中的代码。
示例:
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));
【相关推荐:javascript学习教程】
以上就是JavaScript中两个数字怎么求最大值的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号