Math object in ...LOGIN

Math object in JavaScript

Math mathematical object

The Math object is a static object. In other words: when using the Math object, there is no need to create an instance.

  • Math.PI: Pi.

  • Math.abs(): Absolute value. For example: Math.abs(-9) = 9

  • Math.ceil(): round up (add 1 to the integer and remove the decimal). For example: Math.ceil(10.2) = 11

  • Math.floor(): Round down (remove decimals directly). For example: Math.floor(9.888) = 9

  • Math.round(): Rounding. For example: Math.round(4.5) = 5; Math.round(4.1) = 4

  • Math.pow(x,y): Find the yth power of x. For example: Math.pow(2,3) = 8

  • Math.sqrt(): Find the square root. For example: Math.sqrt(121) = 11

  • Math.random(): Returns a random decimal between 0 and 1. For example: Math.random() = 0.12204467732259783

Note: Find a random number between (min, max). The formula is: Math.random()*(max-min)+min


Example: Random integer between 0-10; find random number between 10-20 Integer; Find a random integer between 20 and 30; Find a random integer between 7 and 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>

Example: Random web page background color

<!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>
Next Section
<!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>
submitReset Code
ChapterCourseware