如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
一个简单的解决方案来创建一个独特的识别是使用一个时间标记,并添加一个随机号码。
下面的功能将产生类型的随机序列: uuid-14d93eb1b9b4533e6. 不需要产生32个字符的随机序列. 在这种情况下,16个字符的随机序列不足以提供JavaScript中的独特 UUID。
var createUUID = function() {
return "uuid-" + ((new Date).getTime().toString(16) + Math.floor(1E7*Math.random()).toString(16));
}
其他回答
GitHub上的JavaScript项目 - https://github.com/LiosK/UUID.js
参见 RFC 4122 http://www.ietf.org/rfc/rfc4122.txt. 功能 产生 RFC 4122 符合 UUIDs. 版本 4 UUIDs (UUIDs 从随机数字) 和版本 1 UUIDs (基于时间的 UUIDs) 可用. UUID 对象允许各种访问 UUID 包括访问 UUID 字段。
我已经建立在这里提到的所有东西,以产生两倍的速度,可携带的所有环境,包括节点,并从Math.random()升级到加密强度的随机性。
function random() {
const
fourBytesOn = 0xffffffff, // 4 bytes, all 32 bits on: 4294967295
c = typeof crypto === "object"
? crypto // Node.js or most browsers
: typeof msCrypto === "object" // Stinky non-standard Internet Explorer
? msCrypto // eslint-disable-line no-undef
: null; // What old or bad environment are we running in?
return c
? c.randomBytes
? parseInt(c.randomBytes(4).toString("hex"), 16) / (fourBytesOn + 1) - Number.EPSILON // Node.js
: c.getRandomValues(new Uint32Array(1))[0] / (fourBytesOn + 1) - Number.EPSILON // Browsers
: Math.random();
}
function uuidV4() { // eslint-disable-line complexity
// If possible, generate a single random value, 128 bits (16 bytes)
// in length. In an environment where that is not possible, generate
// and make use of four 32-bit (4-byte) random values.
// Use crypto-grade randomness when available, else Math.random()
const
c = typeof crypto === "object"
? crypto // Node.js or most browsers
: typeof msCrypto === "object" // Stinky non-standard Internet Explorer
? msCrypto // eslint-disable-line no-undef
: null; // What old or bad environment are we running in?
let
byteArray = c
? c.randomBytes
? c.randomBytes(16) // Node.js
: c.getRandomValues(new Uint8Array(16)) // Browsers
: null,
uuid = [ ];
/* eslint-disable no-bitwise */
if ( ! byteArray) { // No support for generating 16 random bytes
// in one shot -- this will be slower
const
int = [
random() * 0xffffffff | 0,
random() * 0xffffffff | 0,
random() * 0xffffffff | 0,
random() * 0xffffffff | 0
];
byteArray = [ ];
for (let i = 0; i < 256; i++) {
byteArray[i] = int[i < 4 ? 0 : i < 8 ? 1 : i < 12 ? 2 : 3] >> i % 4 * 8 & 0xff;
}
}
byteArray[6] = byteArray[6] & 0x0f | 0x40; // Always 4, per RFC, indicating the version
byteArray[8] = byteArray[8] & 0x3f | 0x80; // Constrained to [89ab], per RFC for version 4
for (let i = 0; i < 16; ++i) {
uuid[i] = (byteArray[i] < 16 ? "0" : "") + byteArray[i].toString(16);
}
uuid =
uuid[ 0] + uuid[ 1] + uuid[ 2] + uuid[ 3] + "-" +
uuid[ 4] + uuid[ 5] + "-" +
uuid[ 6] + uuid[ 7] + "-" +
uuid[ 8] + uuid[ 9] + "-" +
uuid[10] + uuid[11] + uuid[12] + uuid[13] + uuid[14] + uuid[15];
return uuid;
/* eslint-enable no-bitwise */
}
简单的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”
如果您的环境是 SharePoint,则有一个用途函数称为 SP.Guid.newGuid (MSDN 链接创建一个新的 GUID. 该函数位于 sp.init.js 文件中. 如果您重写此函数(从其他私人函数中删除一些其他依赖),并且它看起来如下:
var newGuid = function () {
var result = '';
var hexcodes = "0123456789abcdef".split("");
for (var index = 0; index < 32; index++) {
var value = Math.floor(Math.random() * 16);
switch (index) {
case 8:
result += '-';
break;
case 12:
value = 4;
result += '-';
break;
case 16:
value = value & 3 | 8;
result += '-';
break;
case 20:
result += '-';
break;
}
result += hexcodes[value];
}
return result;
};
这里是一个方法,使用真实的随机通过 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)
))
;
}
此分類上一篇