跨浏览器随机字符串(Math.random()* 1e32).toString(36) [英] Cross browser random string (Math.random()*1e32).toString(36)
问题描述
我使用(Math.random()* 1e32).toString(36)
作为简单的随机字符串生成器。它非常简单,运行良好,满足我的需求(用于ID的时间随机等)
I use (Math.random()*1e32).toString(36)
as a simple random string generator. It is very simple and works well and fullfils my needs (a temporal random to be used for ids, etc)
在chrome,safari,firefox和ie Math.random()* 1e32
生成如下数字: 8.357963780872523e + 31
:-)
In chrome, safari, firefox and ie Math.random()*1e32
generates numbers like: 8.357963780872523e+31
:-)
- 在chrome,safari和firefox中,这样的数字被转换为字符串
(8.357963780872523e + 31).toString(36)
- >221fr2y11ebk4cog84wok
这正是我想要的。 - 但是在ie11中,字符串结果是
6.936gwtrpf69(e + 20)
。
- In chrome, safari and firefox such number is converted into a string
(8.357963780872523e+31).toString(36)
->221fr2y11ebk4cog84wok
which is exactly I want. - However in ie11 the string result is
6.936gwtrpf69(e+20)
.
如何获得相同的字符串 221fr2y11ebk4cog84wok
以交叉浏览器方式从 8.357963780872523e + 31
?
How can I get the same string 221fr2y11ebk4cog84wok
from 8.357963780872523e+31
in a cross browser manner?
BTW:我明白了这个帖子中的随机字符串: JavaScript中的随机字母数字字符串?
BTW: I got the idea of this random string from this thread: Random alpha-numeric string in JavaScript?
推荐答案
请记住 Math.random()
返回介于0和1之间的值(不包括),并且JavaScript中的数字根据IEEE-754有53位尾数,这是一种安全的获取方式随机整数将是
Keeping in mind that Math.random()
returns a value between 0 and 1 (exclusive), and that numbers in JavaScript have 53 bits mantissa as per IEEE-754, a safe way to get a random integer would be
Math.random() * Math.pow(2, 54)
因此可以从获取随机字母数字字符串
So a random alphanumeric string could be obtained from
(Math.random() * Math.pow(2, 54)).toString(36)
请注意,无法保证字符数,可以是1到11之间的任何字符,具体取决于随机值的数量级。
Note that there is no guarantee about the number of characters, which could be anything between 1 and 11 depending on the order of magnitude of the random value.
这篇关于跨浏览器随机字符串(Math.random()* 1e32).toString(36)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!