I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9]
.
(我想要一个由从[a-zA-Z0-9]
随机挑选的字符组成的5个字符串。)
What's the best way to do this with JavaScript?
(用JavaScript做到这一点的最佳方法是什么?)
ask by Tom Lehman translate from so I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9]
.
(我想要一个由从[a-zA-Z0-9]
随机挑选的字符组成的5个字符串。)
What's the best way to do this with JavaScript?
(用JavaScript做到这一点的最佳方法是什么?)
ask by Tom Lehman translate from so
let r = Math.random().toString(36).substring(7); console.log("random", r);
Note: The above algorithm has the following weaknesses:
(注意:以上算法具有以下缺点:)
(由于在对浮点进行字符串化时会删除尾随零,因此它将生成0到6个字符之间的任意位置。)
(这在很大程度上取决于用于对浮点数进行字符串化的算法,该算法极其复杂。)
(See the paper "How to Print Floating-Point Numbers Accurately" .)((请参阅论文“如何准确打印浮点数” 。))
Math.random()
may produce predictable ("random-looking" but not really random) output depending on the implementation.(Math.random()
可能会产生可预测的(“看起来很随机”,但不是真正随机的)输出。)
(当您需要保证唯一性或不可预测性时,结果字符串不适合。)
(即使它产生了6个均匀随机且不可预测的字符,由于生日悖论 ,您也可以期望仅生成大约50,000个字符串后看到重复项。)
(sqrt(36^6) = 46656)((sqrt(36 ^ 6)= 46656))