UUID & GUID
在 JavaScript 中生成唯一标识符。
UUID 简介
- UUID (Universally Unique Identifier): 通用唯一标识符
- GUID (Globally Unique Identifier): 全局唯一标识符
- 格式:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx(32 个十六进制字符,4 个连字符)
使用 crypto.randomUUID()(推荐)
// 现代浏览器和 Node.js 14.17+ 支持
const uuid = crypto.randomUUID();
console.log(uuid); // 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6'
手动实现 UUID v4
function generateUUID() {
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);
});
}
console.log(generateUUID()); // '6ba7b810-9dad-11d1-80b4-00c04fd430c8'
使用 crypto 生成(更安全)
function generateSecureUUID() {
const array = new Uint8Array(16);
crypto.getRandomValues(array);
// 设置版本号和变体位
array[6] = (array[6] & 0x0f) | 0x40; // 版本 4
array[8] = (array[8] & 0x3f) | 0x80; // 变体 1
const hex = Array.from(array)
.map(b => b.toString(16).padStart(2, '0'))
.join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
console.log(generateSecureUUID());
GUID(与 UUID 格式相同)
// GUID 和 UUID 格式相同,只是名称不同
function generateGUID() {
return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).toUpperCase(); // GUID 通常大写
}
console.log(generateGUID()); // '6BA7B810-9DAD-11D1-80B4-00C04FD430C8'
短 UUID
// 生成更短的 ID(不含连字符)
function generateShortId() {
return 'xxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
console.log(generateShortId()); // '6ba7b8109dad'
使用库
uuid 包
npm install uuid
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4();
console.log(id); // 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6'
uuid 包(Node.js)
const { v4: uuidv4 } = require('uuid');
const id = uuidv4();
UUID 版本
| 版本 | 说明 |
|---|---|
| v1 | 基于时间戳和 MAC 地址 |
| v3 | 基于命名空间和 MD5 |
| v4 | 随机生成(最常用) |
| v5 | 基于命名空间和 SHA-1 |