js生成随机数的几个例子

发布时间:2020-09-17编辑:脚本学堂
为大家介绍几个用js生成随机数的小例子,有需要的朋友,可以参考学习下。

js中可以调用Math生成指定范围内的随机数
1)、Math.random() always produces a random number between 0 and 1
2)、Math.random()*2 always produces a random number between 0 and 2
3)、Math.round(Math.random()*2) always produces a random integer between 0 and 2

例1,随机跳转到指定网站。
 

<script type="text/javascript'>
/**
 * 随机调用网址Url
*/
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1="http://www.jb200.com"
var link2="http://www.jbxue.net"
var link3="http://www.jbxue.cn"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
}
</script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>

例2,生成随机数
 

<script language="javascript">
var roundString = function(len){
   var str =  ['a','b','c','d','e','f','h','j','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'];
   var hash = '';
   for(i=0;i<len;i++){
        var r = str[Math.ceil(Math.random()*100)];
        if(r!=undefined)hash +=r;
   }
   if(hash.length<len)hash+=roundString(len-hash.length);
     return hash;
  }
</script>

例3,生成随机字母密码
1、Math.random()生成一个0~1的随机数 0<=Math.random()<1
2、Math.random()*100 则生成一个0~100之间的随机数
3、Math.random()*100 + 100 则生成一个100~200之间的随机数
4、所以Math.random()*m 则生成一个0~m的随机数
 

<script type="text/javascript" language="javascript">
//生成随机字母(随机密码) 
function randomPassword(size)  
{  
var seed = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','m','n',
'p','Q','r','s','t','u','v','w','x','y','z',
'2','3','4','5','6','7','8','9'  
                             );//数组  
        seedlength = seed.length;//数组长度  
        var createPassword = '';  
        for (i=0;i<size;i++) {  
            j = Math.floor(Math.random()*seedlength);  
            createPassword += seed[j];  
        }  
  return createPassword;  
}  
document.write(randomPassword(6));  
</script>