如何生成GUID / UUID?
P粉304704653
P粉304704653 2023-10-08 14:55:18
0
2
587

如何在 JavaScript 中创建 GUID(全局唯一标识符)? GUID / UUID 应至少为 32 个字符,并且应保持在 ASCII 范围内,以避免传递它们时出现麻烦。

我不确定所有浏览器上都可以使用哪些例程,内置随机数生成器的“随机性”和播种方式等等。

P粉304704653
P粉304704653

全部回复(2)
P粉352408038

[于 2023 年 3 月 5 日编辑,以反映生成符合 RFC4122 的 UUID 的最新最佳实践]

crypto.randomUUID() is now standard on all modern browsers and JS runtimes. However, because new browser APIs are restricted to secure contexts, this method is only available to pages served locally (localhost or 127.0.0.1) or over HTTPS.

For readers interested in other UUID versions, generating UUIDs on legacy platforms or in non-secure contexts, there is the uuid module. It is well-tested and supported.

如果上述方法失败,还有这个方法(基于这个问题的原始答案):

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

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: solutions based on Math.random() do not provide good uniqueness guarantees.

P粉190443691

UUID(通用唯一标识符),也称为 GUID(全局唯一标识符),根据 RFC 4122 是旨在提供某些唯一性保证的标识符。

虽然可以通过几行 JavaScript 代码实现符合 RFC 的 UUID(例如,请参阅 @broofa 的回答,如下)有几个常见的陷阱:

  • Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]
  • Use of a low-quality source of randomness (such as Math.random)

因此,鼓励为生产环境编写代码的开发人员使用严格的、维护良好的实现,例如 uuid 模块。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板