</head>
<body>
<h2>JavaScript Math.random()</h2>
<p>点击按钮, getRndInteger(min, max) 会返回 0(包含)到 3(包含)到数字:</p>
<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,3)">点我</button>
<p id="demo"></p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</body>
</html>
Math.floor 向下取整 Math.random 产生随机数
Math.floor(Math.random() * (max - min)) + min;
如果是(min,max],那原文+1依然去掉,在末尾+1,为:
Math.floor(Math.random() * (max - min)) + min+1;
如果是想带有小数的随机数,这里提供思路,产生两位数,然后将个位数转化为小数,十位数就是个位数,以此类推,这样就是有小数的啦。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有