The ability to generate random numbers or alphanumeric strings comes in handy in many situations. You can use it to spawn enemies or food at different locations in the game. You can also use it to suggest random passwords to users or create filenames to save files.
I wrote a tutorial on how to generate random alphanumeric strings in PHP. I said at the beginning of this post that few events are truly random, and the same applies to random number or string generation.
In this tutorial, I will show you how to generate a pseudo-random alphanumeric string in JavaScript.
Let's start by generating random numbers. The first method that comes to mind is Math.random()
, which returns a floating point pseudo-random number. The random number will always be greater than or equal to 0 and less than 1.
The distribution of returned numbers in this range is almost uniform, so this method can generate random numbers well without obvious deviation in daily use. The following is the output of ten calls to the Math.random()
method:
for(let i = 0; i < 10; i++) { console.log(Math.random()); } /* Outputs: 0.9981169188071801 0.7073616929117277 0.05826679080842556 0.30779242012809105 0.37282814053539926 0.8991639574910759 0.5851162879630685 0.40572834956467063 0.5286480734412005 0.07898699710613699 */
As you saw in the previous section, Math.random()
will give us a random number in the range of 0 (inclusive) to 1 (exclusive). Suppose we want a random integer in the range 0 (inclusive) to 100 (exclusive). All we need to do here is multiply the original range by 100.
Taking the first output value of the above code snippet as an example, 0.9981169188071801 will become 99.81169188071801 when multiplied by 100. Now, we can use the Math.floor()
method, which will round down and return the largest integer whose value is less than or equal to 99.81169188071801. In other words, it will give us 99.
The following code snippet will loop 10 times to show all these steps applied to different numbers.
const max_limit = 100; for(let i = 0; i < 10; i++) { let random_float = Math.random(); let scaled_float = random_float * max_limit; let random_integer = Math.floor(scaled_float); let rf_str = random_float.toString().padEnd(20, ' '); let sf_str = scaled_float.toString().padEnd(20, ' '); let ri_str = random_integer.toString().padStart(2, ' '); console.log(`Random Float: ${rf_str} Scaled Float: ${sf_str} Random Integer: ${ri_str}`); } /* Outputs: Random Float: 0.7976037763162469 Scaled Float: 79.76037763162469 Random Integer: 79 Random Float: 0.3794078358214559 Scaled Float: 37.94078358214558 Random Integer: 37 Random Float: 0.5749118617425708 Scaled Float: 57.49118617425708 Random Integer: 57 Random Float: 0.7110572178100005 Scaled Float: 71.10572178100006 Random Integer: 71 Random Float: 0.9157559644743132 Scaled Float: 91.57559644743132 Random Integer: 91 Random Float: 0.8773095295734263 Scaled Float: 87.73095295734264 Random Integer: 87 Random Float: 0.7714603913623834 Scaled Float: 77.14603913623834 Random Integer: 77 Random Float: 0.6431998616346499 Scaled Float: 64.31998616346499 Random Integer: 64 Random Float: 0.7909155691442253 Scaled Float: 79.09155691442254 Random Integer: 79 Random Float: 0.1219575935563590 Scaled Float: 12.19575935563590 Random Integer: 12 */
Now that you understand the logic behind multiplication and rounding, we can write a function to generate random integers within the maximum limit.
function max_random_number(max) { return Math.floor(Math.random() * max); } for(let i = 0; i < 10; i++) { console.log(max_random_number(100)); } /* Outputs: 35 23 92 94 42 9 12 56 40 21 */
What if you want to generate random numbers above a specified minimum but below a maximum?
In this case, you can prepend the minimum value to ensure that the resulting number is at least equal to the minimum value. After that you can simply generate a random number and scale it by max - min
and then add it to the smallest possible value.
function min_max_random_number(min, max) { return min + Math.floor(Math.random() * (max - min)); } for(let i = 0; i < 10; i++) { console.log(min_max_random_number(50, 100)); } /* Outputs: 96 81 95 56 73 72 71 90 51 53 */
Math.random()
method is not suitable for generating cryptographically secure random numbers, but the Crypto.getRandomValues()
method can help us here. This method fills the passed array with cryptographically secure pseudo-random numbers. Keep in mind that the algorithm used to generate these random numbers may vary from user agent to user agent.
As I mentioned before, you need to pass an integer-based TypedArray
to the method so that it fills it with random values. The original contents of the array will be replaced. The following code will fill our ten-element array with random integers.
let random_values = new Uint8Array(10); console.log(random_values); // Outputs: Uint8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] crypto.getRandomValues(random_values); console.log(random_values); // Outputs: Uint8Array(10) [ 207, 209, 1, 145, 70, 111, 21, 141, 54, 200 ]
Unit8Array()
The constructor provides us with an array of ten 8-bit unsigned integers. Array values are all initialized to zero.
Once we pass this array to the getRandomValues()
method, the random number values will remain between 0 and 255. You can use other types of arrays to generate different ranges of random numbers. For example, using the Int8Array()
constructor will give us an array of integer values between -128 and 127. Likewise, using Uint16Array()
will give us an array of integer values up to 65,535. p>
let random_values = new Int8Array(10); console.log(random_values); // Outputs: Int8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] crypto.getRandomValues(random_values); console.log(random_values); // Outputs: Int8Array(10) [ -82, -106, 87, 64, 42, -36, -53, 27, -38, 4 ] let random_values = new Uint16Array(10); console.log(random_values); // Outputs: Uint16Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] crypto.getRandomValues(random_values); console.log(random_values); // Outputs: Uint16Array(10) [ 47615, 60195, 53177, 15169, 215, 4928, 12200, 6307, 30320, 20271 ]
We will now use the knowledge gained in the previous section to generate a random alphanumeric string in JavaScript.
The concept is very simple. We'll start with a string containing all the required characters. In this example, the string will consist of lowercase letters, uppercase letters, and numbers from 0 to 9. As you may already know, we can access a character at a specific position in a string by passing an index value to the string.
To generate a random alphanumeric string, all we need to do is generate a random number and then access the character at that random index to append it to our random string. The following code snippet wraps it all up in a nice little function:
const char_set = 'abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; function max_random_number(max) { return Math.floor(Math.random() * max); } function get_random_string(length) { let random_string = ''; for(let i = 0; i < length; i++) { random_string += char_set[max_random_number(char_set.length - 1)]; } return random_string; } console.log(get_random_string(20)); // Outputs: lgtuRJZolu7AXj4HMoiM console.log(get_random_string(40)); // outputs: scOoal3VXgeAjaHIieolhi2TyWFpAn5bBPPiX6UG
toString()
生成随机字母数字字符串我们可以用来生成随机字母数字字符串的另一种方法是对随机生成的数字使用 toString()
方法。 toString()
方法返回一个表示我们指定数值的字符串。此方法接受可选的 radix
参数,该参数指定要表示数字的基数。值为 2 将返回二进制字符串,值为 16 将返回十六进制字符串。该参数默认值为10。最大值可以为36,因为它涵盖了全部26个字母和10个数字。
以下是针对不同 radix
值对此方法进行几次调用的输出:
let number = 3498650143868; console.log(number.toString(2)); // Outputs: 110010111010010111110011001000110001111100 console.log(number.toString(10)); // Outputs: 3498650143868 console.log(number.toString(16)); // Outputs: 32e97cc8c7c console.log(number.toString(36)); // Outputs: 18n99yoak
您可能已经注意到,随着我们增加 radix
,输出字符串的长度不断减少。在下面的代码片段中,我们将使用上一节中的 max_random_number()
函数来获取随机数。然后,我们将使用 toString()
方法将此随机数转换为字母数字字符串。
function max_random_number(max) { return Math.floor(Math.random() * max); } for(let i = 0; i < 10; i++) { console.log(max_random_number(Number.MAX_SAFE_INTEGER).toString(36)); } /* Outputs: 1tr84s6c2sl 1yj4varyoj7 1zdg9nn0z6r lubrjj1zih 13tt2n5vw9t 1mv6sctjgf yx3fhnznhf 1wj4mdcrqb9 26sir75af2r qdv9xv800t */
如果您想要更大的字母数字字符串并希望它们具有固定长度(例如 40 个字符或 100 个字符)怎么办?在这种情况下,我们可以创建一个循环,不断附加生成的字符串,直到达到所需的长度。
function max_random_number(max) { return Math.floor(Math.random() * max); } function get_random_string(length) { let random_string = ''; while(random_string.length < length) { random_string += max_random_number(Number.MAX_SAFE_INTEGER).toString(36); } return random_string.substring(0, length); } console.log(get_random_string(40)); // Outputs: bn0nfhcsjm18ylzqrm6bo1iktka2aq7qbbl5ybki console.log(get_random_string(100)); // Outputs: rdosjhthsevmk91mj9zvqexz2z0v3pe2beasbzoworanzjg3bfpf975rzfy2fmo6pmj4p69u0x80ce92jh2vljx90g6r0lzd8vb0
在本教程中,我们学习了如何在 JavaScript 中生成随机数和字母数字字符串。借助 Math.random()
方法,在 JavaScript 中生成随机整数很容易。我们所要做的就是缩放输出,使其符合我们所需的范围。如果您希望随机数具有加密安全性,您还可以考虑使用 getRandomValues()
方法。
一旦我们知道如何生成随机数,创建随机字母数字字符串就很容易了。我们需要做的就是弄清楚如何将数字转换为字符。我们在这里使用了两种方法。第一个涉及访问预定义字符串中随机数字索引处的字符。如果您想具体了解随机字母数字字符串中应包含的字符,则此技术非常有用。另一种方法涉及使用 toString()
方法将十进制数转换为不同的基数。这减少了对 max_random_number()
函数的调用。
当然还有更多技术可用于生成随机字母数字字符串。这完全取决于您的需求以及您想要的方法的创意程度。
The above is the detailed content of Generate random numbers and strings in JavaScript. For more information, please follow other related articles on the PHP Chinese website!