php uniqid js 实现
PHP uniqid 的 JavaScript 实现
PHP 的 uniqid 函数生成一个基于当前时间微秒级的唯一 ID。在 JavaScript 中可以通过类似逻辑实现类似功能。

方法一:基于时间戳和随机数
使用 Date.now() 获取时间戳,结合 Math.random() 生成随机数,模拟 uniqid 的行为。

function uniqid(prefix = '', moreEntropy = false) {
const time = Date.now();
const random = Math.floor(Math.random() * 1000000000);
let id = prefix + time.toString(16) + '.' + random.toString(16);
if (moreEntropy) {
id += (Math.random() * 10).toFixed(8).toString();
}
return id;
}
方法二:使用性能计时器
如果需要更高精度,可以使用 performance.now() 替代 Date.now()。
function uniqid(prefix = '', moreEntropy = false) {
const time = performance.now();
const random = Math.floor(Math.random() * 1000000000);
let id = prefix + time.toString(16).replace('.', '') + '.' + random.toString(16);
if (moreEntropy) {
id += (Math.random() * 10).toFixed(8).toString();
}
return id;
}
方法三:模拟 PHP 的完整行为
PHP 的 uniqid 还支持 more_entropy 参数,以下代码更接近 PHP 的实现逻辑。
function uniqid(prefix = '', moreEntropy = false) {
const sec = Math.floor(Date.now() / 1000);
const usec = Math.floor((performance.now() % 1000) * 1000);
const random = Math.floor(Math.random() * 0x1000000);
let id = prefix +
sec.toString(16) +
usec.toString(16).padStart(4, '0') +
random.toString(16).padStart(6, '0');
if (moreEntropy) {
id += '.' + Math.floor(Math.random() * 0x100000000).toString(16);
}
return id;
}
使用示例
console.log(uniqid()); // 类似 "606f7c9b.5a7b3d"
console.log(uniqid('prefix_')); // 类似 "prefix_606f7c9b.5a7b3d"
console.log(uniqid('', true)); // 类似 "606f7c9b.5a7b3d.3acfe4a2"
注意事项
- PHP 的
uniqid是基于微秒级时间戳,JavaScript 的Date.now()只能达到毫秒级精度。 - 如果需要更高的唯一性,可以结合
crypto.getRandomValues()生成更强的随机数。 - 以上实现主要模拟 PHP 的行为,实际项目中可能需要根据具体需求调整。






