网站首页 > 知识剖析 正文
一、方式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
猜你喜欢
- 2025-06-15 LeetCode 力扣官方题解 | 380. O(1) 时间插入、删除和获取随机元素
- 2025-06-15 Python Numpy库详细教程(python numpy.pi)
- 2025-06-15 10款好用的开源 HarmonyOS 工具库
- 2025-06-15 HarmonyOS NEXT异步编程在ArkTS中具体怎么实现?
- 2025-06-15 耗电量减少28%,Chrome浏览器更省电了
- 2025-06-15 小时候玩过的打砖块游戏,大神用javascript写出来了
- 2025-06-15 Chrome修复JS引擎随机数没那么随机的问题
- 2025-06-15 用Three.js学习程序化建模(three.js介绍)
- 2025-06-15 数组(I) - 网络统计学(11)(数组总结)
- 2025-06-15 57.6万代码撕碎AI编程神话,20%「幽灵包」暗藏漏洞,苹果、微软已中招
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)