js实现uuid
生成 UUID 的方法
UUID(Universally Unique Identifier)是一种用于标识信息的唯一标识符。以下是几种在 JavaScript 中生成 UUID 的方法。
使用 crypto.randomUUID()
现代浏览器支持 crypto.randomUUID() 方法,可以快速生成符合 RFC 4122 标准的 UUID。

const uuid = crypto.randomUUID();
console.log(uuid); // 输出类似 "123e4567-e89b-12d3-a456-426614174000"
使用 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()); // 输出类似 "123e4567-e89b-12d3-a456-426614174000"
使用第三方库
如果需要更全面的 UUID 支持,可以使用第三方库如 uuid。
import { v4 as uuidv4 } from 'uuid';
const uuid = uuidv4();
console.log(uuid); // 输出类似 "123e4567-e89b-12d3-a456-426614174000"
简单随机字符串方法
如果对 UUID 的格式要求不高,可以使用简单的随机字符串生成方法。
function simpleUUID() {
return Math.random().toString(36).substring(2) + Date.now().toString(36);
}
console.log(simpleUUID()); // 输出类似 "5h3d7f9k2m"
注意事项
- 使用
crypto.randomUUID()需要浏览器或 Node.js 环境支持。 - 第三方库如
uuid需要安装依赖。 - 简单的随机字符串方法可能不满足严格的 UUID 规范,适用于非关键场景。






