JavaScript高级程序设计学习笔记3: Math对象比较常用的几个方法

方法min():判断一组数中的最小值
方法max():判断一组数中的最大值
方法ceil():向上舍入函数,总是把数字向上舍入最接近的值
方法floor():向下舍入函数,总是把数字向下舍入最接近的值
方法round():标准的传入函数,如果数字与下一个整数的差不超过0.5,则向上舍入,否则向下舍入,也就是四舍五入。
方法random():返回一个0到1之间的随机数,不包括0和1。


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-

transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Math对象</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">   
       
function test() {
    var iMax = Math.max(3, 63, -2, 0, 373);
    alert(iMax);  //输出:373
    var iMin = Math.min(3, 63, -2, 0, 373);
    alert(iMin);  //输出:-2
   
    alert(Math.ceil(25.5));   //输出:26
    alert(Math.round(25.5));  //输出:26
    alert(Math.floor(25.5));  //输出:25

    //返回指定范围内的整数:>=iFirstValue <=iLastValue
    function selectFrom(iFirstValue, iLastValue) {
        var iChoices = iLastValue - iFirstValue + 1;
        return Math.floor(Math.random() * iChoices + iFirstValue);
    }
    var aColors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
    var sColor = aColors[selectFrom(0, aColors.length-1)]; //选择Array中的随机项
    alert(sColor);
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="确定"/>
</body>
</html>

原文地址:https://www.cnblogs.com/gdjlc/p/2086918.html