如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
我们可以使用代替和crypto.getRandomValues以获得这样的输出:
xxxxxxxxxxxxxxxxxxxxxxx
此分類上一篇
如果我们正在寻找一个 opti 解决方案,我们必须用一个序列(32 )取代 crypto.getRandomValues(新 Uint8Array(1))[0]。
const uuidv4 = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
console.log(uuidv4());
要得到这个代码:
函数 uuidv4() { 让比特 = window.crypto.getRandomValues(新 Uint8Array(32)); const randomBytes = () => (比特 = bytes.slice(1)) && bytes[0]; 返回([1e7] + -1e3 + -4e3 + -8e3 + -1e11); 取代(/[018]/g, c => (c ^ randomBytes() & 15 >> c / 4).toString(16) ; } for (var i = 0; i < 10; i++) console.log(uuidv4());
碰撞:
我们可以喜欢谷歌分析,并添加一个时间标签: uuidv4() + "。
其他回答
这里是一个方法,使用真实的随机通过 random.org 生成 RFC4122 如果错误,它会回到浏览器的内置加密图书馆,这应该几乎是相同的好。
async function UUID() {
//get 31 random hex characters
return (await (async () => {
let output;
try {
//try from random.org
output = (await (
await fetch('https://www.random.org/integers/?num=31&min=0&max=15&col=31&base=16&format=plain&rnd=new')
).text())
//get rid of whitespace
.replace(/[^0-9a-fA-F]+/g, '')
;
if (output.length != 31)
throw '';
}
catch {
output = '';
try {
//failing that, try getting 16 8-bit digits from crypto
for (let num of crypto.getRandomValues(new Uint8Array(16)))
//interpret as 32 4-bit hex numbers
output += (num >> 4).toString(16) + (num & 15).toString(16);
//we only want 31
output = output.substr(1);
}
catch {
//failing THAT, use Math.random
while (output.length < 31)
output += (0 | Math.random() * 16).toString(16);
}
}
return output;
})())
//split into appropriate sections, and set the 15th character to 4
.replace(/^(.{8})(.{4})(.{3})(.{4})/, '$1-$2-4$3-$4-')
//force character 20 to the correct range
.replace(/(?<=-)[^89abAB](?=[^-]+-[^-]+$)/, (num) => (
(parseInt(num, 16) % 4 + 8).toString(16)
))
;
}
此分類上一篇
// RFC 4122
//
// A UUID is 128 bits long
//
// String representation is five fields of 4, 2, 2, 2, and 6 bytes.
// Fields represented as lowercase, zero-filled, hexadecimal strings, and
// are separated by dash characters
//
// A version 4 UUID is generated by setting all but six bits to randomly
// chosen values
var uuid = [
Math.random().toString(16).slice(2, 10),
Math.random().toString(16).slice(2, 6),
// Set the four most significant bits (bits 12 through 15) of the
// time_hi_and_version field to the 4-bit version number from Section
// 4.1.3
(Math.random() * .0625 /* 0x.1 */ + .25 /* 0x.4 */).toString(16).slice(2, 6),
// Set the two most significant bits (bits 6 and 7) of the
// clock_seq_hi_and_reserved to zero and one, respectively
(Math.random() * .25 /* 0x.4 */ + .5 /* 0x.8 */).toString(16).slice(2, 6),
Math.random().toString(16).slice(2, 14)].join('-');
最好的方式:
function(
a, b // Placeholders
){
for( // Loop :)
b = a = ''; // b - result , a - numeric variable
a++ < 36; //
b += a*51&52 // If "a" is not 9 or 14 or 19 or 24
? // return a random number or 4
(
a^15 // If "a" is not 15,
? // generate a random number from 0 to 15
8^Math.random() *
(a^20 ? 16 : 4) // unless "a" is 20, in which case a random number from 8 to 11,
:
4 // otherwise 4
).toString(16)
:
'-' // In other cases, (if "a" is 9,14,19,24) insert "-"
);
return b
}
最小化:
function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b}
还有另一种方式来做同样的事情:
function guid() {
var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
var str = "";
for(var i=0; i<36; i++) {
var str = str + ((i == 8 || i == 13 || i == 18 || i == 23) ? "-" : chars[Math.floor(Math.random()*chars.length)]);
};
return str;
}
简单的JavaScript作为这个问题的最佳答案的组合。
var crypto = window.crypto || window.msCrypto || null; // IE11 fix var Guid = Guid || (function() { var EMPTY = '00000000-0000-0000-0000-000000000000'; var _padLeft = function(paddingString, width, replacementChar) { return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' '); }; var _s4 = function(number) { var hexadecimalResult = number.toString(16); return _padLeft(hexadecimalResult, 4, '0'); }; var _cryptoGuid = function() { var buffer = new window.Uint16Array(8); crypto.getRandomValues(buffer); return [_s4(buffer[0]) + _s4(buffer[1]), _s4(buffer[2]), _s4(buffer[3]), _s4(buffer[4]), _s4(buffer[5]) + _s4(buffer[6]) + _s4(buffer[7])].join('-'); }; var _guid = function() { var currentDateMilliseconds = new Date().getTime(); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(currentChar) { var randomChar = (currentDateMilliseconds + Math.random() * 16) % 16 | 0; currentDateMilliseconds = Math.floor(currentDateMilliseconds / 16); return (currentChar === 'x' ? randomChar : (randomChar & 0x7 | 0x8)).toString(16); }); }; var create = function() { var hasCrypto = crypto != 'undefined' && crypto !== null, hasRandomValues = typeof(window.crypto.getRandomValues) != 'undefined'; return (hasCrypto && hasRandomValues) ? _cryptoGuid() : _guid(); }; return { newGuid: create, empty: EMPTY }; })(); // DEMO: Create and show GUID console.log('1. New Guid: ' + Guid.newGuid()); // DEMO: Show empty GUID console.log('2. Empty Guid: ' + Guid.empty);
使用:
主持人( )
“c6c2d12f-d76b-5739-e551-07e6de5b0807”
公平 公平
“00000000-0000-0000-0000-00000000”