如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
下面是使用 crypto.getRandomValues(a)在支持的浏览器(Internet Explorer 11+,iOS 7+,Firefox 21+,Chrome,和Android Chrome)的简单代码。
它避免使用Math.random(),因为这可能会导致碰撞(例如,在 Muxa 实际情况下产生 4000 UUID 的 20 次碰撞)。
function uuid() {
function randomDigit() {
if (crypto && crypto.getRandomValues) {
var rands = new Uint8Array(1);
crypto.getRandomValues(rands);
return (rands[0] % 16).toString(16);
} else {
return ((Math.random() * 16) | 0).toString(16);
}
}
var crypto = window.crypto || window.msCrypto;
return 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/x/g, randomDigit);
}
笔记:
优化为代码可读性,而不是速度,所以它适合,说,几百 UUID 每秒. 它在我的笔记本电脑上在 Chromium 中每秒产生约 10000 uuid() 用 http://jsbin.com/fuwigo/1 来测量性能. 它只使用 8 为 “y” 因为它简化了代码可读性(y 允许为 8, 9, A 或 B)。
其他回答
我发现这个脚本有用于在JavaScript中创建GUID
HTTPS://github.com/addui/GUIDJS
var myGuid = GUID();
原始 URL.createObjectURL 正在产生 UUID. 您可以利用此。
function uuid() {
const url = URL.createObjectURL(new Blob())
const [id] = url.toString().split('/').reverse()
URL.revokeObjectURL(url)
return id
}
我想了解布罗法的答案,所以我扩展了它并添加了评论:
var uuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (match) {
/*
* Create a random nibble. The two clever bits of this code:
*
* - Bitwise operations will truncate floating point numbers
* - For a bitwise OR of any x, x | 0 = x
*
* So:
*
* Math.random * 16
*
* creates a random floating point number
* between 0 (inclusive) and 16 (exclusive) and
*
* | 0
*
* truncates the floating point number into an integer.
*/
var randomNibble = Math.random() * 16 | 0;
/*
* Resolves the variant field. If the variant field (delineated
* as y in the initial string) is matched, the nibble must
* match the mask (where x is a do-not-care bit):
*
* 10xx
*
* This is achieved by performing the following operations in
* sequence (where x is an intermediate result):
*
* - x & 0x3, which is equivalent to x % 3
* - x | 0x8, which is equivalent to x + 8
*
* This results in a nibble between 8 inclusive and 11 exclusive,
* (or 1000 and 1011 in binary), all of which satisfy the variant
* field mask above.
*/
var nibble = (match == 'y') ?
(randomNibble & 0x3 | 0x8) :
randomNibble;
/*
* Ensure the nibble integer is encoded as base 16 (hexadecimal).
*/
return nibble.toString(16);
}
);
};
这个报价返回 5 组 8 个数字从 a-z,0-9 大多数是随机的,但包含日时,并且有一个随机增加的计算器. 你可以指定任何基础你喜欢(六,十,36),默认选择一个随机基础为每个组的 8,在基础范围 16 到 36
function newId(base) { return[ Math.random, function (){ return (newId.last ? windowId.last + Math.random() : Math.random() ) }, Math.random, Date.now, Math.random ].map(function(fn){ return fn().toString(base||(16+(Math.random()*20))).substr(-8); }).join('-'); } var demo = function(base){ document.getElementById('uuid').textContent = newId(base); } demo(16); #uuid { font-family: monospace; font-size: 1.5em; } <p id="uuid"></p> <button onclick="demo(16);">Hex (base 16)</button> <button onclick="demo(36);">Base 36</button> <button onclick="demo(10);">Decimal (base 10)</button> <button onclick="demo();">Random base</button>
它只是扩展 Uint8Array 类型的一个例子,并使用 crypto.getRandomValues() 来产生 UUID 比特值。
class uuid extends Uint8Array {
constructor() {
super(16)
/* Not v4, just some random bytes */
window.crypto.getRandomValues(this)
}
toString() {
let id = new String()
for (let i = 0; i < this.length; i++) {
/* Convert uint8 to hex string */
let hex = this[i].toString(16).toUpperCase()
/* Add zero padding */
while (hex.length < 2) {
hex = String(0).concat(hex)
}
id += hex
/* Add dashes */
if (i == 4 || i == 6 || i == 8 || i == 10 || i == 16) {
id += '-'
}
}
return id
}
}