如何根据提供的范围最小和最大字符在 Javascript 中生成随机数 [英] How to Generate Random numbers in Javascript based on the provided range Minimum and Maximum characters

查看:57
本文介绍了如何根据提供的范围最小和最大字符在 Javascript 中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有点奇怪的要求,我需要生成用户给定长度的随机数.用户可以给出Minimum LengthMaximum Length,我需要生成由这个范围内的字符长度组成的随机数.

I have a bit weird requirement where I need to generate Random numbers of the length that is given by user. User can give Minimum Length and the Maximum Length and I need to generate the random numbers which consist of the character length between this range.

例如,如果 Minimum Length6 并且 Maximum Length10 那么我需要生成字符数必须介于 610 之间的随机数.对于此示例,以下可以是随机生成器:

For example if the Minimum Length is 6 and Maximum Length is 10 then I need to generate the random numbers whose number of characters has to be between the range 6 and 10. For this example following can be the random generators:

123456,
7654321,
12345678,
987654321,
5432109876, etc.

像这样,随机生成器必须包含所提供输入之间的长度.

Like this the Random generators has to contain the length which is between the provided inputs.

我知道如何在一个范围和基于固定字符长度之间创建随机数,但我不知道如何基于可变长度创建.我试图找到答案,但大多数都是基于固定长度和固定范围,找不到我正在寻找的完全匹配.

I know how to create random numbers between a range and based on fixed character length but I don't know how to created based on variable length. I tried finding the answers but most of them are based on the fixed length and fixed range, could not find the exact match that I am looking for.

如果有人能帮助我,那就太好了.

It would be really great if someone can help me with this.

推荐答案

非常感谢大家的解答.这是我使用的方法.

Thanks a lot, everyone for the answer. Here is the approach that I have used.

如果只需要数字的随机数:

If the random numbers with just Numeric is required:

var charset         = "0123456789";
var max_Length      = 5;
var min_Length      = 10;
var charPicker      = Math.floor(Math.random() * (max_Length - min_Length + 1) + min_Length);
var randomId;
for (var i = 0; i < charPicker; i++)
{
    randomId += charset.charAt(Math.floor(Math.random() * charset.length));
}
console.log(randomId);

使用 URL 特定字符更改字母数字和字母数字的字符集,如下所示:

Change the character set for Alphanumeric and Alphanumeric with URL specific characters like this:

var charset         = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charset         = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~()'!*:@,;";

这篇关于如何根据提供的范围最小和最大字符在 Javascript 中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆