如何在 JavaScript 中建立 GUID(全域唯一識別碼)? GUID / UUID 應至少為 32 個字符,並且應保持在 ASCII 範圍內,以避免傳遞它們時出現麻煩。
我不確定所有瀏覽器上都可以使用哪些例程,內建隨機數產生器的「隨機性」和播種方式等等。
P粉3524080382023-10-09 14:12:19
[於 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
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 #the
#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()
P粉1904436912023-10-09 13:09:03
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< /a> 模組。