莫方教程网

专业程序员编程教程与实战案例分享

「前端开发工具分享·建议收藏」JavaScript 随机生成唯一ID

一、方式1:Math.random() 和 Date.now()

(1)完整源码

// 直接使用(缺少时间戳)
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString()); // 4uz4qq4m3a

// 组合时间戳和随机函数使用,减少重复(随机字符串越长越不容易重复哈,也是可行的一个法子)
function generateUniqueId() {  
    const timestamp = Date.now();  
    const random = Math.random().toString(36).substr(2, 9); // 生成一个9位的随机字符串  
    return timestamp + '-' + random;  
}

注意:这种方法简单但可能不够唯一,因为 Math.random() 的随机性有限并且 Date.now()的精度是毫秒级,可能在极短时间内生成重复的ID

(2)结果演示


二、方式2:cryto 模块(Node.js)

这种方法更加靠谱比原生的JavaScript (Math.random())。

const crypto = require('crypto');  
  
function generateUUID() {  
    return crypto.randomBytes(16).toString('hex').match(/.{1,4}/g).join('-');  
}  
  
// 这会生成一个标准的UUID v4格式的字符串

三、方式3:uuid 模块

① 前端安装 uuid 模块

npm install uuid  
# 或者  
yarn add uuid

② JavaScript 引入 uuid

import { v4 as uuidv4 } from 'uuid';  
  
const myUUID = uuidv4();  
console.log(myUUID); // 输出一个版本4的UUID

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言