javascript - 分页计算算法

标签 javascript node.js algorithm

我正在尝试计算分页:

var pagination = {
 total: result.length,
 per_page: itemsPerPage,    // required
 current_page: currentPage, // required
 last_page: users.length / itemsPerPage,    // required
 from: (itemsPerPage * pageNumber) + 1,
 to: itemsPerPage * (pageNumber + 1)           //required
};

假设结果长度为 2,itemsPerPage 为 5,currentPage 为 1,我得到了这个:

total: 2
per_page: 5
current_page: 1
last_page: 0.4
from: 6
to: 10

我觉得有些不对。

最佳答案

要取最大值,您可以使用 last_page 上的 Math.ceil

每页的项目可以是静态的,手动定义的。然后,from 可以是 ((currentPage - 1) * itemsPerPage) + 1

  • 如果当前页为 1,则 ( (1 -1) * 5) + 1 = 1。
  • 第二页:( (2 -1) * 5) + 1 = 6,依此类推。

那么它可以是currentPage * itemsPerPage。例如,如果当前页为 1,则 1 * 5 = 5,如果是第二页,则为:2 * 5 = 10。请看下面的示例:

var pagination = {
 total: result.length,
 per_page: itemsPerPage,    
 current_page: currentPage, 
 last_page: Math.ceil(result.length / itemsPerPage),
 from: ((currentPage -1) * itemsPerPage) + 1,
 to: currentPage  * itemsPerPage
};
Total = 15;
per_page = 5;
currentPage = 1;
last_page = truncate (15 / 5) = 3;
from: ((1-1) * 5) + 1 = 1 //first page
      ((2-1) * 5) + 1 = 6 //second page
to: 1 * 5 = 5 //first page
    2 * 5 = 10 // second page
From 1 to 5 // first page
From 6 to 10 // second page
From 11 to 15 // last page

关于javascript - 分页计算算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39670902/

相关文章:

javascript - 从独立指令访问 $scope

node.js - EADDRINUSE - 仍然无法终止 Node 进程

javascript - 如何同时对表格进行分页并搜索所有内容?

php - 使用 PHP 在 mySQL 中查找多个用户的帐户

c# - 如何生成类似于预付费电话卡 PIN 的唯一 PIN 码

javascript - 加载 javascript 文件的最理想方式是什么?

javascript - 动态更改 header 中的元标记?

javascript - node.js mongodb - collection.find().toArray(callback) - 回调不会被调用

python - 将文本文件列表的记录打乱到一个文件中

javascript - 在javascript中比较和过滤对象数组