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

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


当前回答

对于大数字。

var min_num = 900;
var max_num = 1000;
while(true){
    
    let num_random = Math.random()* max_num;
    console.log('input : '+num_random);
    if(num_random >= min_num){
        console.log(Math.floor(num_random));
       break; 
    } else {
        console.log(':::'+Math.floor(num_random));
    }
}

其他回答

其他解决方案:

(数学随机()*6|0)+1~~(数学随机()*6)+1

联机尝试

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

代码:

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));
}

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

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)

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

简短回答:使用简单的数组即可实现。

您可以在数组元素内交替。

即使您的值不是连续的,此解决方案也有效。值甚至不必是数字。

let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];

这对我来说很有用,并生成类似Python的random.randit标准库函数的值:


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

console.log("Random integer: " + randint(-5, 5));