如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。
我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。
当前回答
我已经建立在这里提到的所有东西,以产生两倍的速度,可携带的所有环境,包括节点,并从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 */
}
其他回答
我找不到使用单一 16-octet TypedArray 和 DataView 的任何答案,所以我认为在 RFC 中创建版本 4 UUID 的下列解决方案将自行存在:
const uuid4 = () => {
const ho = (n, p) => n.toString(16).padStart(p, 0); /// Return the hexadecimal text representation of number `n`, padded with zeroes to be of length `p`
const data = crypto.getRandomValues(new Uint8Array(16)); /// Fill the buffer with random data
data[6] = (data[6] & 0xf) | 0x40; /// Patch the 6th byte to reflect a version 4 UUID
data[8] = (data[8] & 0x3f) | 0x80; /// Patch the 8th byte to reflect a variant 1 UUID (version 4 UUIDs are)
const view = new DataView(data.buffer); /// Create a view backed by a 16-byte buffer
return `${ho(view.getUint32(0), 8)}-${ho(view.getUint16(4), 4)}-${ho(view.getUint16(6), 4)}-${ho(view.getUint16(8), 4)}-${ho(view.getUint32(10), 8)}${ho(view.getUint16(14), 4)}`; /// Compile the canonical textual form from the array data
};
我更喜欢,因为:
它只依赖于标准 ECMAScript 平台的功能,在可能的情况下 - 这只是一个程序它只使用一个单一的泡沫,尽量减少数据的复制,这在理论上应该带来性能优势。
在写这篇文章时, getRandomValues 不是在 Node.js 中的加密对象中实施的东西,但是它具有相同的随机Bytes 功能,可以用来代替它。
这个应用程序的100万次执行只需要32.5秒,这是我从未在浏览器中看到的最快(唯一的解决方案没有漏洞/漏洞)。
/**
* Generates a GUID string.
* @returns {string} The generated GUID.
* @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa
* @author Slavik Meltser.
* @link http://slavik.meltser.info/?p=142
*/
function guid() {
function _p8(s) {
var p = (Math.random().toString(16)+"000000000").substr(2,8);
return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
}
return _p8() + _p8(true) + _p8(true) + _p8();
}
console.time('t');
for (var i = 0; i < 10000000; i++) {
guid();
};
console.timeEnd('t');
算法:
Math.random() 函数返回 0 和 1 之间的十数数,在十数分数点(例如 0.4363923368509859 )之后有 16 个数字。 然后我们采取这个数字并将其转换为 16 个基线(从上面的示例中,我们将获得 0.6fb7687f)。 Math.random(.toString(16 ) 然后我们切断了 0 个预定(.0.6fb7687f => 6fb7687f ) 并获得八个六分数字符的序列。
链接到我的博客上的这篇文章
享受吧:)
您可以使用 npm 包指南、GUID 发电机和验证器。
例子:
Guid.raw();
// -> '6fdf6ffc-ed77-94fa-407e-a7b86ed9e59d'
注意: 此包已被削弱. 使用 uuid 相反。
例子:
const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a'
這裡是一個工作例子. 它生成一個 32 位數的獨特 UUID。
function generateUUID() {
var d = new Date();
var k = d.getTime();
var str = k.toString(16).slice(1)
var UUID = 'xxxx-xxxx-4xxx-yxxx-xzx'.replace(/[xy]/g, function (c)
{
var r = Math.random() * 16 | 0;
v = c == 'x' ? r : (r & 3 | 8);
return v.toString(16);
});
var newString = UUID.replace(/[z]/, str)
return newString;
}
var x = generateUUID()
console.log(x, x.length)
[编辑 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() 的解决方案不提供良好的独特性保证。