For an RFC4122 version 4 compliant solution, this one-liner(ish) solution is the most compact I could come up with:
(对于符合RFC4122版本4的解决方案,此一站式解决方案是我能想到的最紧凑的解决方案:)
function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } console.log(uuidv4());
Update, 2015-06-02 : Be aware that UUID uniqueness relies heavily on the underlying random number generator (RNG).
(更新,2015-06-02 :请注意,UUID的唯一性很大程度上取决于基础随机数生成器(RNG)。)
The solution above uses Math.random()
for brevity, however Math.random()
is not guaranteed to be a high-quality RNG. (上面的解决方案为简洁起见使用Math.random()
,但是不能保证Math.random()
是高质量的RNG。)
See Adam Hyland's excellent writeup on Math.random() for details. (有关详细信息,请参见Adam Hyland 在Math.random()上的出色文章 。)
For a more robust solution, consider something like the uuid module (disclaimer: I'm the author), which uses higher quality RNG APIs where available. (对于更强大的解决方案,请考虑使用uuid模块 (免责声明:我是作者)之类的东西, 该模块在可用时使用更高质量的RNG API。)
Update, 2015-08-26 : As a side-note, this gist describes how to determine how many IDs can be generated before reaching a certain probability of collision.
(更新,2015-08-26 :作为旁注,本要点描述了如何确定在达到一定的碰撞概率之前可以生成多少个ID。)
For example, with 3.26x10 15 version 4 RFC4122 UUIDs you have a 1-in-a-million chance of collision. (例如,使用3.26x10 15版本4 RFC4122 UUID,您有百万分之一的碰撞机会。)
Update, 2017-06-28 : A good article from Chrome developers discussing the state of Math.random PRNG quality in Chrome, Firefox, and Safari.
(更新,2017-06-28 : Chrome开发人员的一篇好文章,讨论了Chrome,Firefox和Safari中Math.random PRNG的质量状态。)
tl;dr - As of late-2015 it's "pretty good", but not cryptographic quality. (tl; dr-截至2015年末,它的“相当好”,但没有加密质量。)
To address that issue, here's an updated version of the above solution that uses ES6, the crypto
API, and a bit of JS wizardry I can't take credit for : (为了解决该问题,这是上述解决方案的更新版本,该解决方案使用ES6, crypto
API和一些JS向导,我对此不以为然 :)
function uuidv4() { return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); } console.log(uuidv4());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…