有没有办法用JavaScript生成指定范围内的随机数?

例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。


当前回答

ES6/Arrow函数版本基于Francis的代码(即顶级答案):

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

其他回答

此函数可以生成介于(包括)最小值和最大值之间的随机整数:

function randomNumber(min, max) {
  if (min > max) {
    let temp = max;
    max = min;
    min = temp;
  }

  if (min <= 0) {
    return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
  } else {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

例子:

randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4

如果起始数字是1,如示例(1-6)所示,则可以使用Math.ceil()方法代替Math.floor()。

Math.ceil(Math.random() * 6)

而不是

Math.floor(Math.random() * 6) + 1

我们不要忘记其他有用的数学方法。

实例

返回1到10之间的随机数:

Math.floor((Math.random() * 10) + 1);

结果可能是:3.

试试看:这里

--

或使用lodash/descore:

_.随机(最小值,最大值)

文件:-罗达什-不受欢迎的

数学不是我的强项,但我一直在做一个项目,我需要在正负之间生成很多随机数。

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}

例如

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

当然,您也可以添加一些验证,以确保您不使用数字以外的任何内容。还要确保最小值始终小于或等于最大值。

范围[a,b]内的加密强随机整数(假设:a<b)

let rand=(a,b)=>a+(b-a+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0console.log(兰特(1,6));