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

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


当前回答

或者,在Undercore

_.random(min, max)

其他回答

var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;

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

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

尝试使用:

函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,6));

重要的

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

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

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