在每种情况下生成 5 位数字的 JavaScript 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2175512/
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-08-22 23:06:04  来源:igfitidea点击:

JavaScript expression to generate a 5-digit number in every case

javascriptrandomexpressiondigit

提问by Christopher Klewes

for my selenium tests I need an value provider to get a 5-digit number in every case. The problem with javascript is that the api of Math.randomonly supports the generation of an 0.starting float. So it has to be between 10000and 99999.

对于我的硒测试,我需要一个值提供者在每种情况下获得一个 5 位数字。javascript 的问题是 apiMath.random仅支持生成0.起始浮点数。所以它必须在10000和之间99999

So it would be easy if it would only generates 0.10000and higher, but it also generates 0.01000. So this approach doesn't succeed:

因此,如果它只会生成0.10000和更高,那将很容易,但它也会生成0.01000. 所以这种方法没有成功:

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

Is it possible to generate a 5-digit number in every case (in an expression!) ?

是否可以在每种情况下(在表达式中!)生成一个 5 位数字?

回答by Rubens Farias

What about:

关于什么:

Math.floor(Math.random()*90000) + 10000;

回答by Guffa

Yes, you can create random numbers in any given range:

是的,您可以在任何给定范围内创建随机数:

var min = 10000;
var max = 99999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;

Or simplified:

或简化:

var num = Math.floor(Math.random() * 90000) + 10000;

回答by miaubiz

if you want to generate say a zipcode, and don't mind leading zeros as long as it's 5 digits you can use:

如果你想生成一个邮政编码,并且不介意前导零,只要它是 5 位数字,你可以使用:

(""+Math.random()).substring(2,7)

回答by Tarek

You can get a random integer inclusive of any given min and max numbers using the following function:

您可以使用以下函数获取包含任何给定最小和最大数字的随机整数:

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

For more examples and other use cases, checkout the Math.random MDN documentation.

有关更多示例和其他用例,请查看Math.random MDN 文档