Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 11 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
您希望它们是真正随机的还是真正独特的?您只能拥有其中之一。
如果您希望它们真正随机,那么只需从 0-9 中随机选择 9 个数字并将它们构建到您的数字中即可。重复的可能性很小,尤其是在大量迭代的情况下。不过,这将是真正随机的。
如果您希望它们真正唯一,那么您必须将每一个都存储在数据库中以确保没有重复。如果生成重复项,则需要重新生成或仅增加数字并重试。如果这就是您正在寻找的内容,最好尝试从 1 开始递增该值。
Do you want them to be truly random or truly unique? You can only have one of these.
If you want them to be truly random, then just randomly pick 9 digits from 0-9 and construct them into your number. There will be a small chance of a duplication, especially over larger numbers of iterations. It will be truly random, though.
If you want them to be truly unique, then you have to store every one in a database to ensure there are no duplicates. If you generate a duplicate, you'll need to regenerate or just increment the number and try again. If this is what you're looking for, it might be good to try just incrementing the value starting at one.
对于唯一的数字,请尝试:
(new Date()).getTime()
除非您在一秒内生成多个数字,否则它永远不会相同。For unique number try:
(new Date()).getTime()
it will never be the same unless you are generating multiple number in a sec.您可以将随机类别与随机类别结合起来。系统时间(或使用系统时间的函数)例如
您还可以在系统时间上使用某些函数,例如
You could combine the Random Class & system time (or a function using system time) e.g.
You could also use some function on the system time e.g.
如果您只想要一个随机的 9 位数字,请尝试:
但是,如果您只想要一个唯一的数字,我会选择使用数据库。
If you just want a random 9-digit number, try:
However, if you just want an unique number I'd go for using a database instead.
您要求的是一个唯一的标识符,它永远不会重复,根据定义,这不是一个随机数。
您可能正在寻找的是 GUID,但它们比 9 位数字长得多(因为如果您从全球范围来看,仅用 9 位数字生成两次相同数字的机会是相当大的)。
无论如何,请检查这篇维基百科文章: http://en.wikipedia.org/wiki/Globally_unique_identifier
编辑:需要澄清的是,GUID 具有一定的随机性。
What you're asking for is a unique identifier, that can never be repeated, this is by definition not a random number.
What you're probably looking for are GUIDs, but these are a lot longer than 9 digits (because the chance on generating the same number twice with only 9 digits is quite large if you look at it from a global scale).
Anyway check this wikipedia article: http://en.wikipedia.org/wiki/Globally_unique_identifier
Edit: to clarify, GUIDs have somewhate of a random nature.