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 #the
uuid
#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());
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, 或 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. 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
uuiduuid
module. It is well-tested and #the#supported.
Note: The use of any
do not provide good uniqueness guarantees.###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()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, 或 b]Math.random
)因此,鼓勵為生產環境編寫程式碼的開發人員使用嚴格的、維護良好的實現,例如 uuid 模組。