如何创建 GUID/UUID [英] How to create a GUID / UUID

查看:39
本文介绍了如何创建 GUID/UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 JavaScript 中创建全局唯一标识符.我不确定在所有浏览器上都有哪些例程可用,如何随机"?并播种了内置的随机数生成器等

I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.

GUID/UUID 应至少为 32 个字符,并且应保持在 ASCII 范围内,以避免在传递它们时出现问题.

The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.

推荐答案

这里的大多数读者都希望使用uuid 模块.它经过充分测试和支持.

Most readers here will want to use the uuid module. It is well-tested and supported.

crypto.randomUUID() 函数是一个新兴的标准,在 Node.js支持浏览器数量.

如果这些都不适合你,有这个方法(基于这个问题的原始答案):

If neither of those work for you, there is this method (based on the original answer to this question):

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());

注意:对于 此处解释得最清楚.TL;DR:基于 Math.random() 的解决方案不能提供良好的唯一性保证.

Note: The use of any UUID generator that relies on Math.random() is strongly discouraged (including snippets featured in previous versions of this answer) for reasons best-explained here. TL;DR: Math.random()-based solutions do not provide good uniqueness guarantees.

这篇关于如何创建 GUID/UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆