前言
前几天有个老铁提了一个需求,让我给他在前端静态页面做一个随机数的显示,用做订单编号,简单几行代码即可实现,见下文
按钮形式
<script> function Num() { document.getElementById("field").value=Math.floor(Math.random()*5+5) + Math.ceil(Math.random()*10)/10 } </script> <button onclick="Num()">输出5-10的随机数</button> <input type="text" id="field">
文本形式
<script language="javascript"> var a=parseInt(Math.random()*100); [xss_clean]("输出随机数:",a); </script>
效果
按钮形式(可多次按下) |
文本形式 |
语法
Math.ceil() | 向上取整。 |
Math.floor() | 向下取整。 |
Math.round() | 四舍五入。 |
Math.random() | [0.0 ~ 1.0) 区间一个伪随机数 |
通过组合上面的简单语法可以生成更复杂的语法:
Math.ceil(Math.random()*10) 获取从1到10的随机整数 ,取0的概率极小。
Math.round(Math.random()) 可均衡获取0到1的随机整数。
Math.floor(Math.random()*10) 可均衡获取0到9的随机整数。
Math.round(Math.random()*10) 获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
因此上文的Math.floor(Math.random()*5+5) + Math.ceil(Math.random()*10)/10
可以生成5-10的一位随机数