欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript 生成指定范圍數(shù)值隨機(jī)數(shù)

 更新時(shí)間:2009年01月09日 18:14:47   作者:  
查手冊后才知道, 介紹的信息少得可憐吶, 沒有介紹生成 m-n 范圍的隨機(jī)數(shù)..., 就只是給你一個(gè) Math.random() 了事.
不過經(jīng)過俺的小小努力之后, 終于讓俺摸著門道嘍, 問題也就理所當(dāng)然滴解決掉.
然后就寫了個(gè)公式, 這樣應(yīng)該可以消失掉這個(gè)用法了, 公式:
1. 從1開始 至 任意值
linenum
parseInt(Math.random()*上限+1);
2. 從任意值開始 至 任意值
linenum
parseInt(Math.random()*(上限-下限+1)+下限);
上面的公式使用了 parseInt(), 因此要加1; 如果使用 Math.ceil() 則不需要加1, 俺習(xí)慣于這樣寫...
目錄:
1. 演示1 (直接進(jìn)行生成隨機(jī)數(shù)操作)
2. 演示2 (寫成函數(shù)進(jìn)行生成隨機(jī)數(shù)操作)
1. 演示1 (直接進(jìn)行生成隨機(jī)數(shù)操作)
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 (寫成函數(shù)進(jìn)行生成隨機(jī)數(shù)操作)
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;
}
} // 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 />

相關(guān)文章

最新評論