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

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


当前回答

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

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

其他回答

根据@Francisc的答案中的int版本添加具有固定精度版本的float:

function randomFloatFromInterval (min, max, fractionDigits) {
  const fractionMultiplier = Math.pow(10, fractionDigits)
  return Math.round(
    (Math.random() * (max - min) + min) * fractionMultiplier,
  ) / fractionMultiplier
}

so:

randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...

对于int答案

randomFloatFromInterval(1,3,0) // => 1, 2, 3

我在搜索用TypeScript编写的随机数生成器,在阅读了所有答案后,我写了这个,希望它对TypeScript程序员有用。

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   

尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。

代码:

function getR(lower, upper) {

  var percent = (Math.random() * 100);
  // this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
  //now you have a percentage, use it find out the number between your INTERVAL :upper-lower 
  var num = ((percent * (upper - lower) / 100));
  //num will now have a number that falls in your INTERVAL simple maths
  num += lower;
  //add lower to make it fall in your INTERVAL
  //but num is still in decimal
  //use Math.floor>downward to its nearest integer you won't get upper value ever
  //use Math.ceil>upward to its nearest integer upper value is possible
  //Math.round>to its nearest integer 2.4>2 2.5>3   both lower and upper value possible
  console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}

函数randomIntFromInterval(min,max){//包括min和maxreturn Math.floor(Math.random()*(max-min+1)+min)}常量rndInt=随机IntFromInterval(1,6)控制台日志(rndInt)

它的“额外”之处在于它允许不以1开头的随机间隔。例如,你可以得到一个从10到15的随机数。灵活性

jsfiddle:https://jsfiddle.net/cyGwf/477/

随机整数:要获得最小值和最大值之间的随机整数,请使用以下代码

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

随机浮点数:要获得最小值和最大值之间的随机浮点数,请使用以下代码

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random