Wie erstelle ich eine GUID (Globally Unique Identifier) in JavaScript? GUIDs/UUIDs sollten mindestens 32 Zeichen lang sein und im ASCII-Bereich bleiben, um Probleme bei der Übergabe zu vermeiden.
Ich bin mir nicht sicher, welche Routinen in allen Browsern verfügbar sind, wie hoch die „Zufälligkeit“ des integrierten Zufallszahlengenerators ist, wie er gesetzt wird usw.
[于 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 模块。