app直播源代码,JS生成随机数,生成指定位数的随机数

发布时间 2023-06-19 14:11:41作者: 云豹科技-苏凌霄

app直播源代码,JS生成随机数,生成指定位数的随机数

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

​ 代码解析及执行结果:

//获取随机数,小数第一位可能为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)
  )
);

 

 以上就是 app直播源代码,JS生成随机数,生成指定位数的随机数,更多内容欢迎关注之后的文章