JavaScript产生随机数

JS产生随机数主要运用Math对象,以下为常用方法:

  • Math.ceil();  //向上取整。
  • Math.floor();  //向下取整。
  • Math.round();  //四舍五入。
  • Math.random();  //0.0 ~ 1.0 之间的一个随机数。【包含0不包含1】 //比如0.3562871938739

因此,要想利用random产生随机整数就需要对结果进行取整操作:

  • Math.ceil(Math.random()*10);      // 获取从1到10的随机整数 ,取0的概率极小。
  • Math.round(Math.random());   //可均衡获取0到1的随机整数
  • Math.round(Math.random()*10);  //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半
  • Math.floor(Math.random()*10);  //可均衡获取0到9的随机整数

结论,生成[min,max]的随机数公式为:

  • parseInt(Math.random()*(max-min)+min,10);
  • Math.floor(Math.random()*(max-min+1)+min);




猜你喜欢

转载自blog.csdn.net/didudidudu/article/details/80093288