JS生成指定位数的随机

<html>
<script>
//获取指定位数的随机数 function getRandom(num){ var random = Math.floor((Math.random()+Math.floor(Math.random()*9+1))*Math.pow(10,num-1)); } //调用随机数函数生成10位数的随机数 getRandom(10);
</script>
</html>

实现思路(文末有代码过程及运行结果),以获取10位随机数为例:html

一、Math.random()函数能够得到0到1之间的小数,Math.pow(10,10)函数进行幂运算等价于10的10次方,Math.floor()函数向下取整去除小数位;浏览器

二、组合起来则能够得到一个10位的随机数:Math.floor(Math.random()*Math.pow(10,10));dom

三、可是,若是Math.randow()的第一位小数位为0则可能得到的是9位随机数;函数

四、将Math.randow()加1,排除第一位小数位为0的状况,相应的幂运算减一位spa

Math.floor((Math.random()+1))*Math.pow(10,9));调试

如此将得到一个10位的随机数,可是都将以1开头;code

五、为了开头也能随机取数,能够将1替换为Math.floor(Math.random()*9+1);htm

六、最终的代码以下所示:blog

Math.floor((Math.random()+Math.floor(Math.random()*9+1))*Math.pow(10,9));ip

如此就能够得到一个彻底随机的10位随机数了;

//获取随机数,小数第一位可能为0
console.log(Math.random());
//获取10位随机数,若是小数第一位为0则只有9位数
console.log(Math.floor(Math.random()*Math.pow(10,10)));
//随机数+1,解决小数第一位为0的状况
//可是会致使随机数的第一位老是为1
console.log(Math.floor((Math.random()+1)*Math.pow(10,9)));
//将随机数+1也改成随机加上1~9之间的数字,解决第一位老是为1的问题
console.log(Math.floor((Math.random()+Math.floor(Math.random()*9+1))*Math.pow(10,9)));

Chrome浏览器调试运行结果-----------------------------------------------------------------------------
获取随机数,小数第一位可能为0:
0.097574709201919
获取10位随机数,若是小数第一位为0则只有9位数:
623721160
随机数+1,解决小数第一位为0的状况:
可是会致使随机数的第一位老是为1:
1242782126
将随机数+1也改成随机加上1~9之间的数字,解决第一位老是为1的问题:
7671051679