<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位随机数为例:

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

2、组合起来则可以获得一个10位的随机数:Math.floor(Math.random()*Math.pow(10,10));

3、但是,如果Math.randow()的第一位小数位为0则可能获得的是9位随机数;

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

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

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

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

6、最终的代码如下所示:

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

如此就可以获得一个完全随机的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

 

posted on 2017-05-03 23:00  竹子的梦想在路上  阅读(10866)  评论(0编辑  收藏  举报