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

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


当前回答

基本上像骰子一样返回1-6,

return Math.round(Math.random() * 5 + 1);

其他回答

根据@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

对于大数字。

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

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

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)

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

这已经晚了九年,但randojs.com让这成为了一个简单的一行:

rando(1, 6)

您只需要将其添加到html文档的头部,就可以轻松地使用随机性做任何事情。数组中的随机值、随机jquery元素、对象中的随机财产,甚至在需要时防止重复。

<script src="https://randojs.com/1.0.0.js"></script>

重要的

The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.

如果你想得到一个介于1(且只有1)和6之间的随机整数,你可以计算:

const rndInt=数学地板(Math.random()*6)+1控制台日志(rndInt)

哪里:

1是起始编号6是可能结果的数量(1+start(6)-end(1))