js实现guid
GUID/UUID 实现方法
在 JavaScript 中生成 GUID(全局唯一标识符)或 UUID(通用唯一标识符)有多种方法。以下是几种常见实现方式:
使用 crypto API(推荐)
现代浏览器支持 crypto.randomUUID() 方法,这是最标准且高效的方式:
const uuid = crypto.randomUUID();
console.log(uuid); // 输出类似 "36b8f84d-df4e-4d49-b662-bcde71a8764f"
手动实现 UUID v4
如果环境不支持 crypto.randomUUID(),可以手动实现符合 RFC 4122 标准的 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());
使用第三方库
流行的第三方库如 uuid 提供了更完整的 UUID 支持:
// 安装:npm install uuid
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4();
性能优化版本
对于需要高性能的场景,可以使用以下优化版本:

function fastUUID() {
const buf = new Uint32Array(4);
crypto.getRandomValues(buf);
return `${buf[0].toString(16)}-${buf[1].toString(16).substr(1)}-4${buf[2].toString(16).substr(1)}-${(8 + (buf[3] % 4)).toString(16)}${buf[3].toString(16).substr(1)}-${buf[4].toString(16)}${buf[5].toString(16)}${buf[6].toString(16)}`;
}
注意事项
浏览器兼容性方面需要注意:
crypto.randomUUID()需要 Chrome 92+、Firefox 95+、Safari 15.4+- 旧版浏览器需要使用 polyfill 或手动实现
Node.js 环境从 14.17.0 开始也支持 crypto.randomUUID()。
安全性考虑:
- 避免使用
Math.random()生成关键标识符 - 密码学安全场景必须使用
crypto.getRandomValues()






