如何在JavaScript中创建GUID(全球独特识别器)?GUID/UUID应该至少有32个字符,并且应该保持在ASCII范围内,以避免在通过它们时遇到麻烦。

我不确定在所有浏览器上有哪些习惯,如何“随机”和种植内置的随机号码发电机等。


当前回答

最好的方式:

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}

其他回答

不要使用 Math.random 在任何情况下,因为它产生一个非加密的随机数字来源。

下面的解决方案使用crypto.getRandomValues

function uuidv4() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    // tslint:disable-next-line: no-bitwise
    const r =
      (window.crypto.getRandomValues(new Uint32Array(1))[0] *
        Math.pow(2, -32) * 16) |
      0;
    // tslint:disable-next-line: no-bitwise
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

此链接有助于您了解由 Fortify Scanner 投下的不安全的随机性。

基于布罗法的答案,我有自己的答案:

这里是使用 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());

ES6 样品

const guid=()=> {
  const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);     
  return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}

UUID 与内置时间标签(发行器/发行器)

我在 date.now() 中的毫秒内使用时间印(在 Node.js 图书馆中,我将稍后提到,我从 process.hrtime.bigint() 中的 nanoseconds 使用时间印),然后随机添加 5 位数(10000-90000 )到时间印链的尽头。

由于我们将时间标记插入 UUID 线上,我们获得一个功能(好或坏 - 取决于任务) - 能够轻松地从 UUID 提取此时间标记。

Node.js 编辑

基准

点击此处查看JsBench

OK,使用 uuid 包,并支持版本 1, 3, 4 和 5 UUID,做:

yarn add uuid

然后:

const uuidv1 = require('uuid/v1');
uuidv1(); // ⇨ '45745c60-7b1a-11e8-9c9c-2d42b21b1a3e'

您也可以使用完整的选项:

const v1options = {
  node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
  clockseq: 0x1234,
  msecs: new Date('2011-11-01').getTime(),
  nsecs: 5678
};
uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'

要了解更多信息,请参阅 npm 页面。