function getRandom(num){
var random = Math.floor((Math.random()+Math.floor(Math.random()*9+1))*Math.pow(10,num-1));
}
//调用随机数函数生成10位数的随机数
getRandom(10);
实现思路(文末有代码过程及运行结果),以获取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位随机数了;