3

可能重复:
在特定范围内的 Javascript 中生成随机数?

假设我想生成一个从 50 到 100 的随机数。

我知道有:

Math.random()

但我只能找到从 1 到“x”的方法

4

2 回答 2

10

MDN 上Math.random()

// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
于 2012-12-21T22:07:59.010 回答
2

I believe this would also work:

function randomInt(min,range) {
return Math.floor((Math.random()*(range+1))+min)
}

In your case min would be 50 and range would be 50

于 2012-12-21T22:18:24.507 回答