Method to generate random numbers: First use the "random()" method to return a random number between 0 and 1, and then multiply the obtained random number by the specified number plus the specified number to obtain Random numbers within the specified range; finally use the "floor()" method to return the largest integer less than or equal to the specified interval.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Use Math.floor()
in combination with Math.random()
.
This simple line of code will return you a number between 1 and 6 (all inclusive):
Math.floor(Math.random() * 6 + 1)
There are 6 possible results here: 1, 2, 3, 4 ,5,6.
Extended information:
The random() method can return a random number between 0 ~ 1.
<html> <body> <script type="text/javascript"> document.write(Math.random()) //一个可能结果:0.3564017841844467 </script> </body> </html>
The floor() method returns the largest integer less than or equal to x. If the passed parameter is an integer, the value is unchanged.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>document</title> </head> <body> <p id="demo">单击按钮将不同的数值降到离它最近的整数。</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var a=Math.floor(0.60); var b=Math.floor(0.40); var c=Math.floor(5); var d=Math.floor(5.1); var e=Math.floor(-5.1); var f=Math.floor(-5.9); var x=document.getElementById("demo"); x.innerHTML=a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e + "<br>" + f; } </script> </body> </html>
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to generate two random numbers in javascript. For more information, please follow other related articles on the PHP Chinese website!