打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
一篇文章带你了解JavaScript随机数

回复“前端”即可获赠前端相关学习资料

鱼和熊掌不可兼得!

一、Math.random()

Math.random() 返回0到1之间的随机数(包括0,不包括1)。

语法

Math.random();            // returns a random number
代码
<!DOCTYPE html><html>    <title>项目</title>
<body style="background-color: aqua;"> <h1>JavaScript Math.random()</h1>
<p>单击按钮以显示0(含)和1(不含)之间的随机数:</p>
<button onclick="myFunc()">Click</button>
<p id="result"></p>
<script> function myFunc() { document.getElementById('result').innerHTML = Math.random(); }</script>
</body></html>

Math.random() 总是返回小于1的数字。

二、JavaScript 随机整数

Math.random() 和 Math.floor() 一起使用,可以返回一个随机整数。

案例1:返回一个从0到9的随机整数

Math.floor(Math.random() * 10);     // returns a number between 0 and 9
代码
<!DOCTYPE html><html>    <title>项目</title>
<body style="background-color: aqua;">
<p>单击按钮以显示0到9之间的随机数:</p>
<button onclick="myFunc()">Click</button>
<p id="result"></p>
<script> function myFunc() { let x = Math.floor(Math.random() * 11); document.getElementById("result").innerHTML = x; // 下面代码依次替换相对于的js代码,实现以下效果 }</script>
</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;">
<p>单击按钮以显示0到9之间的随机数:</p>
<button onclick="myFunc()">Click</button>
<p id="result"></p>
<script> function myFunc() { document.getElementById("result").innerHTML = getRandom(0, 10); }
function getRandom(min, max) { return Math.floor(Math.random() * (max - min)) + min; }</script>
</body></html>

JavaScript函数总是返回一个随机数在min(包括)和max(包括)之间:

<!DOCTYPE html><html>  <title>项目</title>   <body style="background-color: aqua;">
<p>单击按钮以显示0到10之间的随机数:</p>
<button onclick="myFunc()">Click</button>
<p id="result"></p>
<script> function myFunc() { document.getElementById("result").innerHTML = getRandom(0, 10); }
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }</script>
</body></html>

四、总结

本文主要介绍了JavaScript 随机数(Random)函数的应用,介绍了如何去取一个区间的随机数,以及随机整数。通过用丰富的案例帮助大家更好理解。

希望大家可以根据文章的内容,积极尝试,有时候看到别人实现起来很简单,但是到自己动手实现的时候,总会有各种各样的问题,切勿眼高手低,勤动手,才可以理解的更加深刻。

使用JavaScript 语言,方便大家更好理解,希望对大家的学习有帮助。

------------------- End -------------------

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
内置对象Math.random()随机数方法的三种示例
JS生成随机数(random()函数)
javascript中的Math.random()用法
JAVA基础:随机整数的生成
Lua 随机数生成问题
JAVA的Random类
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服