当前位置:首页 > PHP

php uniqid js 实现

2026-02-15 12:01:46PHP

PHP uniqid 的 JavaScript 实现

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

php uniqid js 实现

方法一:基于时间戳和随机数

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

php uniqid js 实现

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 的行为,实际项目中可能需要根据具体需求调整。

标签: phpuniqid
分享给朋友:

相关文章

php实现上传

php实现上传

PHP 文件上传实现 HTML 表单设置 创建一个包含文件上传字段的 HTML 表单,确保表单的 enctype 属性设置为 multipart/form-data,这是文件上传必需的设置。 &l…

php 购物车实现

php 购物车实现

数据库设计 购物车功能通常需要设计数据库表存储商品和用户信息。常见的表包括products(商品表)、users(用户表)和cart(购物车表)。cart表通常包含字段:id(主键)、user_id(…

php实现异步

php实现异步

PHP 实现异步的方法 PHP 本身是同步执行的脚本语言,但可以通过以下方法模拟异步操作或实现异步效果: 使用多进程(pcntl_fork) 通过 pcntl_fork 创建子进程实现异步,适用于…

php实现上传图片

php实现上传图片

上传图片的基本流程 PHP 实现图片上传功能需要处理文件接收、验证、保存等步骤。以下是具体实现方法。 创建 HTML 表单 在 HTML 中创建一个表单,设置 enctype="multipart…

php 实现单链表

php 实现单链表

单链表的基本概念 单链表是一种线性数据结构,由节点组成,每个节点包含数据域和指向下一个节点的指针域。链表的头节点是访问整个链表的入口。 单链表的节点类实现 在PHP中,可以通过类来定义链表节…

php 队列的实现

php 队列的实现

PHP 队列的实现方法 使用数据库实现队列 创建一个数据表存储队列任务,包含任务ID、状态、创建时间等字段。通过SQL语句实现任务的入队和出队操作。 // 入队操作 INSERT INTO queu…