JS 生成随机数

本文发布于 9 年前,部分内容可能已经失去参考价值。

0 <= n < 1

var n = Math.random();

0 <= n < 100

var n = Math.random() * 100;

10 <= n < 100

var n = Math.random() * (100 - 10) + 10;

若需要生成整数,则使用 Math.floor() 方法进行下舍入即可:

0 <= n < 100(n 为整数):

var n = Math.floor(Math.random() * 100);

10 <= n < 100(n 为整数):

var n = Math.floor(Math.random() * (100 - 10) + 10);

换句话说,

0 <= n <= 99(n 为整数):

var n = Math.floor(Math.random() * (99 + 1));

10 <= n <= 99(n 为整数):

var n = Math.floor(Math.random() * (99 + 1 - 10) + 10);

总结公式,要生成 min <= n <= max 的整数:

var n = Math.floor(Math.random() * (max + 1 - min) + min);
xoyozo 9 年前
转载请注明出处
云服务器 精选特惠
可能相关的内容