← 中文资源

简体中文版本

对内存数组分页

将数组切分为指定页并返回页码、总页数及是否还有后续结果等元数据,符合多数列表接口的结构。

阅读英文原文

实现说明

整个示例围绕函数 offset、paginate组织。 返回值是携带 offset、current、safeLimit、totalPages 的对象。

使用要点

  • 把 paginate 当作 API:导入它,其余代码可以忽略。

常见问题

paginate 会修改传入的参数吗?

不会修改。入参只读,返回值是全新构造的。

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 offset、paginate。

主签名形如 export function paginate(items, page = 1, limit = 20)

核心语句

const totalPages = Math.max(1, Math.ceil(items.length / safeLimit));
const current = Math.min(Math.max(page, 1), totalPages);
const safeLimit = Math.min(Math.max(limit, 1), 100);

代码示例

export function paginate(items, page = 1, limit = 20) {
  const safeLimit = Math.min(Math.max(limit, 1), 100);
  const totalPages = Math.max(1, Math.ceil(items.length / safeLimit));
  const current = Math.min(Math.max(page, 1), totalPages);
  const offset = (current - 1) * safeLimit;
  return {
    data: items.slice(offset, offset + safeLimit),
    page: current,
    limit: safeLimit,
    totalPages,
    hasMore: current < totalPages,
  };
}