在 JavaScript 中生成指定范围内的随机数

本教程介绍了如何在 JavaScript 中的指定范围内生成随机数。我们将使用 Math.random() 函数生成随机数,然后将其移动到指定范围内的数字。

Math.random() 函数

该函数返回浮点伪随机数,范围在 0(包括)到 1(不包括)之间,并且在该范围内具有大致均匀的分布。但是它不会返回密码安全的数字。

JavaScript 在指定范围内生成随机数的算法

  • 生成一个介于 0 和 1 之间的数字,并将其存储在名为 rand 的变量中。
  • 计算总范围 range 为 max-min+1
  • 将 range 乘以 rand 并将其添加到 min 以获得指定范围内的随机数。

示例代码


function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min);
}

getRandomIntInclusive(2,5);

输出:

4