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

如何在 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. 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

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

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, 或 b]
  • Use of a low-quality source of randomness (such as Math.random)

因此,鼓勵為生產環境編寫程式碼的開發人員使用嚴格的、維護良好的實現,例如 uuid 模組。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板