JavaScript随机

1.我们可以通过Math.random()返回 0(包括)至1(不包括)之间的随机数

 Math.random();
  • 但是它返回的数总是小于1。

2.我们可以借助Math.random()Math.floor()一起使用用于返回随机整数。
例如:

Math.floor(Math.random() * 10);  //返回 0 - 9 之间的数  因为floor是向下舍入的。
Math.floor(Math.random() * 10) + 1 ; //返回 1 -10 之间的数
Math.floor(Math.random() * 101); // 返回 0 - 100之间的数

** 3.除了上述以外,我们还可以自定义随机函数**

  • 始终返回 大于等于 min 小于max之间的随机数。
function getRandInteger(min,max){
	return Math.floor(Math.random() * (max - min ) ) + min ;
}
  • 始终返回 大于等于 min 小于等于max之间的随机数。
function getRandInteger(min,max){
	return Math.floor(Math.random() * (max - min + 1) ) + min ;
}

版权声明:本文为qq_43968060原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_43968060/article/details/114408411