如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
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);
});
}
其他回答
对于我的使用案例,我需要 ID 世代,保证在全球范围内是独一无二的;没有例外.我与问题斗争了一段时间,并提出了一个名为 TUID (真正独一无二的 ID ) 的解决方案。
我正在使用下面的功能:
function NewGuid()
{
var sGuid = "";
for (var i=0; i<32; i++)
{
sGuid += Math.floor(Math.random()*0xF).toString(0xF);
}
return sGuid;
}
这个是基于日期,并添加一个随机的补充到“保证”的独特性。
它很好地用于CSS识别器,总是返回类似的东西,并且很容易被黑客攻击:
uid-139410573297741
var getUniqueId = function (prefix) {
var d = new Date().getTime();
d += (parseInt(Math.random() * 100)).toString();
if (undefined === prefix) {
prefix = 'uid-';
}
d = prefix + d;
return d;
};
基于布罗法的作品,我添加了一些更多的随机性,通过添加时间表到 math.random():
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = parseFloat('0.' + Math.random().toString().replace('0.', '') + new Date().getTime()) * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
基于布罗法的答案,我有自己的答案:
这里是使用 crypto.getRandomValues 的加密更强的版本。
函数 uuidv4() { const a = crypto.getRandomValues(新 Uint16Array(8)); let i = 0; return '00-0-4-1-000'.replace(/[^-]/g, s => (a[i++] + s * 0x10000 >> s).toString(16).padStart(4, '0') ); } console.log(uuidv4());
这里是使用 Math.random 的更快版本,使用几乎相同的原则:
函数 uuidv4() { return '00-0-4-1-000'.replace(/[^-]/g, s => ((Math.random() + ~~s) * 0x10000 >> s).toString(16).padStart(4, '0') ); } console.log(uuidv4());