js 实现uuid
UUID 的实现方法
在 JavaScript 中生成 UUID(通用唯一标识符)可以通过多种方式实现。以下是几种常见的方法:
使用 crypto.randomUUID()
现代浏览器支持 crypto.randomUUID() 方法,这是最简单且符合标准的方式:

const uuid = crypto.randomUUID();
console.log(uuid); // 输出类似 "1a2b3c4d-5e6f-7g8h-9i0j-1k2l3m4n5o6p"
使用 crypto.getRandomValues()
如果环境不支持 randomUUID(),可以通过 crypto.getRandomValues() 生成随机字节并转换为 UUID 格式:

function generateUUID() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
console.log(generateUUID());
使用第三方库
许多第三方库如 uuid 提供了跨平台的 UUID 生成功能:
import { v4 as uuidv4 } from 'uuid';
const uuid = uuidv4();
console.log(uuid);
时间戳与随机数结合
在不支持 crypto 的环境下,可以通过时间戳和随机数模拟 UUID:
function simpleUUID() {
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(simpleUUID());
注意事项
- 使用
crypto.randomUUID()是最推荐的方式,因为它符合 RFC 4122 标准且安全性高。 - 如果需要支持旧版浏览器或 Node.js 环境,第三方库(如
uuid)是更好的选择。 - 自行实现的随机数方法可能无法保证唯一性和安全性,仅适用于非关键场景。






