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.
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)
[于 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
or127.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.如果上述方法失败,还有这个方法(基于这个问题的原始答案):
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 onMath.random()
do not provide good uniqueness guarantees.UUID(通用唯一标识符),也称为 GUID(全局唯一标识符),根据 RFC 4122 是旨在提供某些唯一性保证的标识符。
虽然可以通过几行 JavaScript 代码实现符合 RFC 的 UUID(例如,请参阅 @broofa 的回答,如下)有几个常见的陷阱:
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]Math.random
)因此,鼓励为生产环境编写代码的开发人员使用严格的、维护良好的实现,例如 uuid 模块。