JavaScript中的Math數學對象

Math數學物件

Math物件是一個靜態對象,換句話說:在使用Math對象,不需要建立實例。

  • Math.PI:圓周率。

  • Math.abs():絕對值。如:Math.abs(-9) = 9

  • Math.ceil():向上取整(整數加1,小數去掉)。如:Math.ceil(10.2) = 11

  • Math.floor():向下取整(直接去掉小數)。如:Math.floor(9.888) = 9

  • Math.round():四捨五入。如:Math.round(4.5) = 5;    Math.round(4.1) = 4

  • Math.pow(x,y):求x的y次方。如:Math.pow(2,3) = 8

  • Math.sqrt():求平方根。如:Math.sqrt(121) = 11

  • Math.random():傳回0到1之間的隨機小數。如:Math.random() = 0.12204467732259783

註:求(min,max)之間的隨機數。公式為:Math.random()*(max-min)+min


例子:0-10之間的隨機整數;求10-20之間的隨機整數;求20到30之間的隨機整數;求7到91之間的隨機整數

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>
        <script>
            //求两个整数之间的随机整数
            //定义随机数的函数
            function getRandom(min,max){
                //求随机数
                var random =Math.random()*(max-min)+min;
                //向下取整
                random = Math.floor(random);
                //输出结果
                document.write(random+"<hr>");
            }
            //调用函数
            getRandom(0,100);
            getRandom(5,89);
            getRandom(100,999);
        </script>
    </head>
    <body>
    </body>
</html>

實例:隨機網頁背景色

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>

    </head>
    <body>
    </body>
</html>
<script>
    var min = 100000;
    var max = 999999;
    var random = Math.random() *(max-min)+min; 
     //向下取整
    random = Math.floor(random);
    document.body.bgColor = "#"+random;
</script>
繼續學習
||
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //求两个整数之间的随机整数 //定义随机数的函数 function getRandom(min,max){ //求随机数 var random =Math.random()*(max-min)+min; //向下取整 random = Math.floor(random); //输出结果 document.write(random+"<hr>"); } //调用函数 getRandom(0,100); getRandom(5,89); getRandom(100,999); </script> </head> <body> </body> </html>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!