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

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


当前回答

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

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

其他回答

获取0到400之间的随机整数

let rand=数学舍入(Math.random()*400)document.write(兰特)

获取200到1500之间的随机整数

让范围={min:200,max:1500}设delta=范围.max-范围.minconst rand=数学舍入(range.min+Math.random()*delta)document.write(兰特)

使用函数

函数randBetween(最小值,最大值){设delta=最大值-最小值return Math.round(min+Math.random()*delta)}document.write(randBetween(10,15));

//JavaScript ES6箭头函数常量randBetween=(最小值,最大值)=>{设delta=最大值-最小值return Math.round(min+Math.random()*delta)}document.write(randBetween(10,20))

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

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

这应该是有效的:

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

重要的

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

或者,在Undercore

_.random(min, max)