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

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


当前回答

尝试使用:

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

其他回答

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

如果起始数字是1,如示例(1-6)所示,则可以使用Math.ceil()方法代替Math.floor()。

Math.ceil(Math.random() * 6)

而不是

Math.floor(Math.random() * 6) + 1

我们不要忘记其他有用的数学方法。

其他解决方案:

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

联机尝试

或者,在Undercore

_.random(min, max)

这应该是有效的:

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