php uniqid js 实现
PHP uniqid 的 JavaScript 实现
PHP 的 uniqid 函数生成基于当前时间微秒级的唯一 ID,默认情况下返回 13 位字符串。以下是 JavaScript 中的等效实现方法:

方法一:基于时间戳与随机数
function uniqid(prefix = "", moreEntropy = false) {
const timestamp = Date.now().toString(16);
const random = Math.floor(Math.random() * 0x10000).toString(16);
let id = prefix + timestamp + random;
if (moreEntropy) {
const extra = Math.floor(Math.random() * 0x1000000).toString(16);
id += "." + extra;
}
return id;
}
方法二:精确微秒级实现(Node.js 环境)
在 Node.js 中可使用 process.hrtime() 获取更高精度时间:

function uniqid(prefix = "", moreEntropy = false) {
const [sec, nanosec] = process.hrtime();
const timestamp = (sec * 1000 + Math.floor(nanosec / 1000000)).toString(16);
const random = Math.floor(Math.random() * 0x10000).toString(16);
let id = prefix + timestamp + random;
if (moreEntropy) {
const extra = Math.floor(Math.random() * 0x1000000).toString(16);
id += "." + extra;
}
return id;
}
浏览器环境注意事项
浏览器端无法获取真正的微秒级精度,但可通过 performance.now() 提高精度:
function uniqid(prefix = "", moreEntropy = false) {
const time = performance.now().toString(16).replace(".", "");
const random = Math.floor(Math.random() * 0x10000).toString(16);
let id = prefix + time + random;
if (moreEntropy) {
const extra = Math.floor(Math.random() * 0x1000000).toString(16);
id += "." + extra;
}
return id;
}
输出示例
console.log(uniqid()); // 类似 "6065f3a7b1a4"
console.log(uniqid("pre_")); // 类似 "pre_6065f3a7b1b2"
console.log(uniqid("", true)); // 类似 "6065f3a7b1c3.12d4e5"






