javascript 生成2个数字之间的随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13997793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:26:14  来源:igfitidea点击:

Generate random number, between 2 numbers?

javascriptrandom

提问by Alex

Possible Duplicate:
Generating random numbers in Javascript in a specific range?

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

Say I wanted to generate a random number from 50 to 100.

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

I know there's:

我知道有:

Math.random()

but I could only find ways to go from 1 to 'x'

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

回答by Sirko

From MDN on Math.random():

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

回答by simonthumper

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

在您的情况下, min 为 50, range 为 50