一、方式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;
}