如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
這只是一個概念,大多數人肯定可以以多種方式改進,但並不像我認為那樣緩慢。
总的来说,这个代码包含在毫秒内编码的黑客时间表(有某些黑客它给了12个数字,所以代码甚至在2527-06-24,但不是在5138-11-16之后工作),这意味着它是可编码的。
我知道这可能会缩短,性能提高,但我对结果感到高兴(除了MAC地址)。
目前Nanoseconds = () => { return nodeMode? process.hrtime.bigint() : BigInt(Date.now() * 1000000); } nodeFindMacAddress = () => { // 提取 MAC 地址 const 界面 = require('os').network 界面(); let result = null; for (index in interfaces) { let entry = interfaces[index]; entry.forEach(item => { if (item.mac!== '00:00:00:00:00:00') { result = '-'
其他回答
在这里,你可以找到一个非常小的功能,产生UUID。
最后一个版本是:
function b(
a // Placeholder
){
var cryptoObj = window.crypto || window.msCrypto; // For Internet Explorer 11
return a // If the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
cryptoObj.getRandomValues(new Uint8Array(1))[0] // in which case
% 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // Replacing
/[018]/g, // zeroes, ones, and eights with
b // random hex digits
)
}
对于想要 RFC 4122 版本 4 符合速度考虑的解决方案的人(少数电话到 Math.random()):
var rand = Math.random; 函数 UUID() { var nbr, randStr = "; do { randStr += (nbr = rand()).toString(16).substr(3, 6); } 同时(randStr.length < 30); 返回( randStr.substr(0, 8) + "-" + randStr.substr(8, 4) + "-4" + randStr.substr(12, 3) + "-" + ((nbr*4♰0) +8).toString(16) + // [89ab] randStr.substr(15, 3) + "-" + rand
上面的功能应该在速度和随机性之间保持适当的平衡。
UUID 与内置时间标签(发行器/发行器)
我在 date.now() 中的毫秒内使用时间印(在 Node.js 图书馆中,我将稍后提到,我从 process.hrtime.bigint() 中的 nanoseconds 使用时间印),然后随机添加 5 位数(10000-90000 )到时间印链的尽头。
由于我们将时间标记插入 UUID 线上,我们获得一个功能(好或坏 - 取决于任务) - 能够轻松地从 UUID 提取此时间标记。
Node.js 编辑
基准
点击此处查看JsBench
这可能对某人有用......
var d = new Date().valueOf();
var n = d.toString();
var result = '';
var length = 32;
var p = 0;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (var i = length; i > 0; --i){
result += ((i & 1) && n.charAt(p) ? '<b>' + n.charAt(p) + '</b>' : chars[Math.floor(Math.random() * chars.length)]);
if(i & 1) p++;
};
HTTPS://jsfiddle.net/j0evrdf1/1/
根據 RFC 4122 的 UUID (Universally Unique IDentifier),也被稱為 GUID (Globally Unique IDentifier),是為提供某些獨特性保證而設計的識別。
虽然可以在JavaScript代码的几个行中实施符合RFC的UUID(例如,请参见 @broofa的答案,下面),但有几个常见的漏洞:
无效 ID 格式(UUID 必须是“xxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx”的格式,其中 x 是 [0-9, a-f] M 是 [1-5] 的格式,而 N 是 [8, 9, a 或 b] 使用低质量的随机性来源(如 Math.random)
因此,开发人员为生产环境编写代码被鼓励使用严格,良好的实施,如新模块。