javascript
用javascript生成指定范围的随机数
1. 從1開始 至 任意值
linenum
parseInt(Math.random()*上限+1);
2. 從任意值開始 至 任意值
linenum
parseInt(Math.random()*(上限-下限+1)+下限);
上面的公式使用了 parseInt(), 因此要加1; 如果使用 Math.ceil() 則不需要加1, 習慣于這樣寫...
1. 示例1 (直接進行生成隨機數操作)
linenum
<script type="text/javascript">
//<![CDATA[
window.οnlοad=function(){
var n=na=nb=nc="";
n=parseInt(Math.random()*10+1);
na=parseInt(Math.random()*(20-11+1) + 11);
nb=parseInt(Math.random()*100+1);
nc=parseInt(Math.random()*(100-51+1) + 51);
var o=document.getElementsByTagName("input");
o[0].value=n;
o[1].value=na;
o[2].value=nb;
o[3].value=nc;
} // shawl.qiu script
//]]>
</script>
1-10: <input type="text" /><br />
11-20: <input type="text" /><br />
1-100: <input type="text" /><br />
51-100: <input type="text" /><br />?
2. 示例2 (寫成函數進行生成隨機數操作)
linenum
<script type="text/javascript">
//<![CDATA[
window.οnlοad=function(){
var o=document.getElementsByTagName("input");
o[0].value=fRandomBy(10);
o[1].value=fRandomBy(11, 20);
o[2].value=fRandomBy(1, 100);
o[3].value=fRandomBy(51, 100);
}
function fRandomBy(under, over){
switch(arguments.length){
case 1: return parseInt(Math.random()*under+1);
case 2: return parseInt(Math.random()*(over-under+1) + under);
default: return 0;
}
}
//]]>
</script>
1-10: <input type="text" /><br />
11-20: <input type="text" /><br />
1-100: <input type="text" /><br />
51-100: <input type="text" /><br />?
轉載于:https://www.cnblogs.com/NoRoad/archive/2010/10/18/1854427.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的用javascript生成指定范围的随机数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高通全系列手机处理器深度解析 (升级选手
- 下一篇: SpringBoot-短信验证码-快速入