用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.onload=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.onload=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 /> 

posted @ 2010-10-18 15:21  NoRoadZH  阅读(401)  评论(0编辑  收藏  举报