如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
最简单的功能来做到这一点:
function createGuid(){
let S4 = () => Math.floor((1+Math.random())*0x10000).toString(16).substring(1);
let guid = `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
return guid.toLowerCase();
}
其他回答
var guid = createMyGuid();
function createMyGuid()
{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
这里是一个类似的 RFC4122 版本 4 符合的解决方案,解决了这个问题,通过将第一个 13 个 hex 数字以一个 hex 部分的时光,并一旦被一个 hex 部分的微秒从 pageload. 因此,即使 Math.random 是相同的种子,两个客户将不得不产生 UUID 相同的数量的微秒从 pageload (如果高性能
const generateUUID = () => { let d = new Date().getTime(), d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now() * 1000)) || 0; return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { let r = Math.random() * 16; if (d > 0) { r = (d + r) % 16 | 0; d = Math.floor(d / 16); } else { r = (d2 + r) % 16 | 0; d2 = Math.floor(d2 / 16); } return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16); }); }; const onClick = (e) => document.getElementById('uuid').textContent = generateUUID(); document.getElementById('generateUUID').addEventListener('click', onClick); onClick(); #uuid { font-family: monospace; font-size: 1.5em; } <p id="uuid"></p> <button id="generateUUID">Generate UUID</button>
只有在任何人落下谷歌正在寻找一个小用途图书馆的情况下,ShortId满足了这个问题的所有要求,它允许指定允许的字符和长度,并保证不序列,不重复的线条。
为了使这一点更为真实的答案,该图书馆的核心使用下列逻辑来制作其简短的ID:
function encode(lookup, number) {
var loopCounter = 0;
var done;
var str = '';
while (!done) {
str = str + lookup( ( (number >> (4 * loopCounter)) & 0x0f ) | randomByte() );
done = number < (Math.pow(16, loopCounter + 1 ) );
loopCounter++;
}
return str;
}
/* Generates the short id */
function generate() {
var str = '';
var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001);
if (seconds === previousSeconds) {
counter++;
} else {
counter = 0;
previousSeconds = seconds;
}
str = str + encode(alphabet.lookup, version);
str = str + encode(alphabet.lookup, clusterWorkerId);
if (counter > 0) {
str = str + encode(alphabet.lookup, counter);
}
str = str + encode(alphabet.lookup, seconds);
return str;
}
我没有编辑这只是反映这个方法的最基本部分,所以上面的代码包含一些额外的逻辑从图书馆. 如果你对它正在做的一切好奇,请看看来源: https://github.com/dylang/shortid/tree/master/lib
[编辑 2021-10-16 以反映 RFC4122 符合 UUID 的最新最佳做法]
大多数读者在这里会想使用 uuid 模块,它已被测试和支持。
如果其中没有一个为您工作,则有这个方法(基于这个问题的原始答案):函数 uuidv4() {返回([1e7]+-1e3+-4e3+-8e3+-1e11)。代替(/[018]/g,c =>(c ^ crypto.getRandomValues(新Uint8Array(1))[0] & 15 >> c / 4).toString(16) ; } console.log(uuidv4());
注意:依靠 Math.random() 的任何 UUID 发电机的使用是由于这里最好的解释而受到强烈的拒绝(包括此答案的以前版本中显示的剪辑) TL;DR:基于 Math.random() 的解决方案不提供良好的独特性保证。
我想了解布罗法的答案,所以我扩展了它并添加了评论:
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);
}
);
};