📜  在 javascript 中生成 guid(1)

📅  最后修改于: 2023-12-03 14:50:57.304000             🧑  作者: Mango

在 JavaScript 中生成 GUID

GUID(全局唯一标识符)是一种用于在计算机系统中标识唯一实体的标准。在 JavaScript 中,我们可以使用不同的方法生成 GUID。下面列出了一些常用的方法。

方法一:使用第三方库

使用第三方库可以简化生成 GUID 的过程。以下是几个常用的第三方库:

  1. uuid:一个流行的用于生成 UUID(通用唯一标识符)的库。
  2. guid:另一个简单易用的库,用于生成 GUID。

这些库提供了方便的函数来生成 GUID,可以通过 npm 安装并引入使用。

// 使用 uuid
const { v4: uuidv4 } = require('uuid');
const guid = uuidv4();

// 使用 guid
const Guid = require('guid');
const guid = Guid.create().toString();
方法二:使用标准API

在某些情况下,使用现有的标准 JavaScript API 也可以生成 GUID。以下是几个选项:

  1. Math.random():使用随机数生成一个简单的 GUID。
function generateGuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

const guid = generateGuid();
  1. crypto.getRandomValues():在支持的浏览器中,可以使用 crypto API 生成更安全的随机数。
function generateGuid() {
  const buf = new Uint16Array(8);
  crypto.getRandomValues(buf);
  return (
    pad4(buf[0]) + pad4(buf[1]) + '-' + pad4(buf[2]) + '-' + pad4(buf[3]) + '-' +
    pad4(buf[4]) + '-' + pad4(buf[5]) + pad4(buf[6]) + pad4(buf[7])
  );
}

function pad4(num) {
  let ret = num.toString(16);
  while (ret.length < 4) {
    ret = '0' + ret;
  }
  return ret;
}

const guid = generateGuid();
方法三:使用浏览器特性

在浏览器中生成 GUID 时,可以使用浏览器提供的一些特性。

  1. performance.now():使用浏览器性能API生成时间戳,并将其转换为 GUID。
function generateGuid() {
  let d = performance.now();
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}

const guid = generateGuid();
  1. crypto 对象:在支持的浏览器中,crypto.getRandomValues() 函数也可以用于生成 GUID,与上面的方法二类似。
function generateGuid() {
  const buf = new Uint16Array(8);
  crypto.getRandomValues(buf);
  return (
    pad4(buf[0]) + pad4(buf[1]) + '-' + pad4(buf[2]) + '-' + pad4(buf[3]) + '-' +
    pad4(buf[4]) + '-' + pad4(buf[5]) + pad4(buf[6]) + pad4(buf[7])
  );
}

function pad4(num) {
  let ret = num.toString(16);
  while (ret.length < 4) {
    ret = '0' + ret;
  }
  return ret;
}

const guid = generateGuid();

以上就是在 JavaScript 中生成 GUID 的几种常用方法。根据具体的使用场景选择合适的方法,可以方便地生成唯一的标识符。