一、Math.random()
Math.random() 返回0到1之间的随机数(包括0,不包括1)。
语法:
Math.random(); // returns a random number
**代码**:
1 2<!DOCTYPE html> 3<html> 4 <title>项目</title> 5 6 <body style="background-color: aqua;"> 7 <h1>JavaScript Math.random()</h1> 8 9 <p>单击按钮以显示0(含)和1(不含)之间的随机数:</p> 10 11 <button onclick="myFunc()">Click</button> 12 13 <p id="result"></p> 14 15 <script> 16 function myFunc() { 17 document.getElementById('result').innerHTML = Math.random(); 18 } 19</script> 20 21 </body> 22</html>
Math.random() 总是返回小于1的数字。

二、JavaScript 随机整数
Math.random() 和 Math.floor() 一起使用,可以返回一个随机整数。
案例1:返回一个从0到9的随机整数
Math.floor(Math.random() * 10); // returns a number between 0 and 9
代码:
1 2<!DOCTYPE html> 3<html> 4 <title>项目</title> 5 6 <body style="background-color: aqua;"> 7 8 <p>单击按钮以显示0到9之间的随机数:</p> 9 10 <button onclick="myFunc()">Click</button> 11 12 <p id="result"></p> 13 14 <script> 15 function myFunc() { 16 let x = Math.floor(Math.random() * 11); 17 document.getElementById("result").innerHTML = x; // 下面代码依次替换相对于的js代码,实现以下效果 18 } 19</script> 20 21 </body>

案例2:返回一个从0到99的随机整数
Math.floor(Math.random() * 100); // returns a number between 0 and 9

案例3:返回一个从0到100的随机整数
Math.floor(Math.random() * 101); // returns a number between 0 and 10

案例4:返回一个从11到20的随机整数
Math.floor((Math.random() * 10) + 11); // returns a number between 11 and 20

案例5:返回一个从1到100的随机整数
Math.floor(Math.random() * 100) + 1; // returns a number between 1 and 100

三、恰当随机函数(min(包括)和max(排除)之间)。
上面的例子中看到的,创建一个合适的随机函数用于所有的随机整数可能是个好主意。
JavaScript函数总是返回一个随机数在min(包括)和max(排除)之间:
<!DOCTYPE html> <html> <title>项目</title> <body style="background-color: aqua;">1<!DOCTYPE html> 2<html> 3 <title>项目</title> 4 5 <body style="background-color: aqua;"> 6 7 <p>单击按钮以显示0到9之间的随机数:</p> 8 9 <button onclick="myFunc()">Click</button> 10 11 <p id="result"></p> 12 13 <script> 14 function myFunc() { 15 document.getElementById("result").innerHTML = getRandom(0, 10); 16 } 17 18 function getRandom(min, max) { 19 return Math.floor(Math.random() * (max - min)) + min; 20 } 21</script> 22 23 </body> 24</html>``` 25 26 27 28JavaScript函数总是返回一个随机数在min(包括)和max(包括)之间: 29
</script> </body> </html> ```1<p>单击按钮以显示0到10之间的随机数:</p> 2 3<button onclick="myFunc()">Click</button> 4 5<p id="result"></p> 6 7<script> 8 function myFunc() { 9 document.getElementById("result").innerHTML = getRandom(0, 10); 10 } 11 12 function getRandom(min, max) { 13 return Math.floor(Math.random() * (max - min + 1)) + min; 14 }

四、总结
本文主要介绍了JavaScript 随机数(Random)函数的应用,介绍了如何去取一个区间的随机数,以及随机整数。通过用丰富的案例帮助大家更好理解。
希望大家可以根据文章的内容,积极尝试,有时候看到别人实现起来很简单,但是到自己动手实现的时候,总会有各种各样的问题,切勿眼高手低,勤动手,才可以理解的更加深刻。
使用JavaScript 语言,方便大家更好理解,希望对大家的学习有帮助。
-------------------********************************** End **********-------------**-----********-**********************************

往期精彩文章推荐:

欢迎各位大佬点击链接加入群聊【helloworld开发者社区】:https://jq.qq.com/?_wv=1027&k=mBlk6nzX进群交流IT技术热点。
