js生成隨機(jī)數(shù)(指定范圍)的實(shí)例代碼
來(lái)源:易賢網(wǎng) 閱讀:628 次 日期:2016-07-29 14:01:01
溫馨提示:易賢網(wǎng)小編為您整理了“js生成隨機(jī)數(shù)(指定范圍)的實(shí)例代碼”,方便廣大網(wǎng)友查閱!

下面小編就為大家?guī)?lái)一篇js生成隨機(jī)數(shù)(指定范圍)的實(shí)例代碼。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。

1、隨機(jī)生成4位數(shù)的隨機(jī)數(shù)

<script language="javascript">

/**

* 隨機(jī)生成4位的隨機(jī)數(shù)

* http://www.yulu.jb51.net

*/

document.write(parseInt(10*Math.random()));  //輸出0~10之間的隨機(jī)整數(shù)

document.write(Math.floor(Math.random()*10+1));  //輸出1~10之間的隨機(jī)整數(shù)

function RndNum(n){

 var rnd="";

 for(var i=0;i<n;i++)

   rnd+=Math.floor(Math.random()*10);

 return rnd;

}

document.write(RndNum(4));  //輸出指定位數(shù)的隨機(jī)數(shù)的隨機(jī)整數(shù)

</script>

2、隨機(jī)生成指定的數(shù)據(jù)范圍的隨機(jī)數(shù)

1)、從1開始 至 任意值

parseInt(Math.random()*上限+1);

2)、從任意值開始至任意值

<script>

parseInt(Math.random()*(上限-下限+1)+下限); 

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; 

  } 

document.write(fRandomBy(1,100));  //輸出指定范圍內(nèi)的隨機(jī)數(shù)的隨機(jī)整數(shù)

</script>

//給既定文本框按規(guī)則付不同的值[引申]

<script>

window.onload=function(){ 

  var o=document.getElementsByTagName('input'); 

  o[0].value=fRandomBy(1,10); 

  o[1].value=fRandomBy(11,20); 

  o[2].value=fRandomBy(1,100); 

  o[3].value=fRandomBy(51,100); 

}

</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 />

3、擴(kuò)展例子:

<html>

<head>

<title>Math-生成隨機(jī)數(shù)的例子-www.jb51.net</title>

</head>

<body>

<script language="javascript" type="text/javascript">

total = 0

for(i=1;i<=5000;i++){

  num=Math.random();

  total +=num

}

average = total/5000;

average = Math.round(average*1000)/1000;

document.write("<h1>平均數(shù):"+average+"</h1>")

</script>

</body>

</html>

以上這篇js生成隨機(jī)數(shù)(指定范圍)的實(shí)例代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:js生成隨機(jī)數(shù)(指定范圍)的實(shí)例代碼
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)