js 实现uuid
生成 UUID 的方法
使用 crypto.randomUUID()
现代浏览器支持 crypto.randomUUID() 方法,直接生成符合 RFC 4122 标准的 UUID v4:
const uuid = crypto.randomUUID();
console.log(uuid); // 输出类似 "d1a3e5f7-9b8c-4d2e-a6f0-3c7b9e8d2a1f"
使用第三方库 uuid
安装 uuid 库(Node.js 或浏览器环境均可):
npm install uuid
代码示例:
import { v4 as uuidv4 } from 'uuid';
const uuid = uuidv4(); // 生成 UUID v4
console.log(uuid);
手动实现 UUID v4
以下是一个简单的 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);
});
}
const uuid = generateUUID();
console.log(uuid);
使用 URL.createObjectURL
浏览器环境中可利用 URL.createObjectURL 生成唯一标识符(非标准 UUID):

const uuid = URL.createObjectURL(new Blob()).split('/').pop();
console.log(uuid); // 输出类似 "blob:http://origin/550e8400-e29b-41d4-a716-446655440000"
注意事项
crypto.randomUUID()是原生 API,性能最佳且符合标准。- 手动实现的 UUID 可能不符合严格的 RFC 4122 规范,适用于简单场景。
- 生产环境推荐使用
uuid库,支持多种 UUID 版本和跨平台兼容性。






