You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现两页共用相同项目索引的分页功能?

实现双页重复项目索引的分页方案(用于PDF打印左右页)

需求明确:需将大型表格拆分为左右页用于PDF打印,要求连续两页的项目索引完全一致。以下是给定参数及预期效果:

参数示例

  • itemsPerPage = 5(单组数据条数)
  • totalItems = 16(总数据条数)
  • totalPages = 8(总页数,每组数据对应2页)

预期分页对应关系

page: indexOfItems
0: 0,1,2,3,4
1: 0,1,2,3,4
2: 5,6,7,8,9
3: 5,6,7,8,9
4: 10,11,12,13,14
5: 10,11,12,13,14
6: 15
7: 15

预期控制台输出

"Current page 0: 0 - 4."
"Current page 1: 0 - 4."
"Current page 2: 5 - 9."
"Current page 3: 5 - 9."
"Current page 4: 10 - 14."
"Current page 5: 10 - 14."
"Current page 6: 15 - 15."
"Current page 7: 15 - 15."

现有代码问题分析

你提供的TypeScript代码存在两处核心问题:

  • 奇偶页的索引计算逻辑完全错误,偶数页用(currentPage - 1) * pageSize会出现负数索引,奇数页计算逻辑也不符合分组重复的需求
  • 函数内部引用了未作为参数传入的itemsPerPage变量,会导致运行报错

正确算法思路

核心逻辑是将当前页码除以2取整,得到对应的分组索引,再通过分组索引计算该组的起始和结束索引:

  1. 计算分组索引:groupIndex = Math.floor(currentPage / 2)
  2. 计算该组起始索引:startIndex = groupIndex * itemsPerPage
  3. 计算该组结束索引:endIndex = Math.min(startIndex + itemsPerPage - 1, totalItems - 1)
  4. 总页数计算:Math.ceil(totalItems / itemsPerPage) * 2(每组数据对应2页)

修复后的TypeScript代码

const paginate = (totalItems: number, currentPage: number, itemsPerPage: number) => {
    // 计算当前页所属的分组索引(每2页为一组)
    const groupIndex = Math.floor(currentPage / 2);
    // 计算该组的起始索引
    const startIndex = groupIndex * itemsPerPage;
    // 计算该组的结束索引,不超过总数据的最后一条索引
    const endIndex = Math.min(startIndex + itemsPerPage - 1, totalItems - 1);

    return {
        totalItems,
        currentPage,
        itemsPerPage,
        startIndex,
        endIndex
    };
};

const numberOfItems: number = 16;
const itemsPerPage: number = 5;
// 总页数 = 分组数 * 2
const numberOfPages: number = Math.ceil(numberOfItems / itemsPerPage) * 2;

let pg: any = {};
for (let i = 0; i < numberOfPages; i++) {
    pg = paginate(numberOfItems, i, itemsPerPage);
    console.log(`Current page ${pg.currentPage}: ${pg.startIndex} - ${pg.endIndex}.`);
}

运行结果

执行上述代码后,控制台将输出完全符合预期的结果,满足连续两页索引一致的PDF打印需求。

内容的提问来源于stack exchange,提问作者Elo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:40:42