简体   繁体   English

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

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

for my selenium tests I need an value provider to get a 5-digit number in every case.对于我的硒测试,我需要一个值提供者在每种情况下获得一个 5 位数字。 The problem with javascript is that the api of Math.random only supports the generation of an 0. starting float. javascript 的问题是Math.random的 api 只支持生成一个0.起始浮点数。 So it has to be between 10000 and 99999 .所以它必须在1000099999之间。

So it would be easy if it would only generates 0.10000 and higher, but it also generates 0.01000 .因此,如果它只生成0.10000或更高的值会很容易,但它也会生成0.01000 So this approach doesn't succeed:所以这种方法没有成功:

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

Is it possible to generate a 5-digit number in every case (in an expression!) ?是否可以在每种情况下(在表达式中!)生成一个 5 位数字?

关于什么:

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

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;

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

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

What about this?那这个呢?

 var generateRandomNDigits = (n) => { return Math.floor(Math.random() * (9 * (Math.pow(10, n)))) + (Math.pow(10, n)); } generateRandomNDigits(5)

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 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM