如何使用javascript计算每页的项目数及其索引?

时间:2017-07-21 08:21:36

标签: javascript pagination

我正在为表格构建分页系统,并希望显示像1 to 5 of 14 entries这样的文本我有以下代码



var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 1;

var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);

var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);

var end = start + numberOfItemsPerPage - 1;

console.log(`${start} to ${end} of ${totalItemsCount}`);




现在,当每页的项目数可以平均分配项目总数时,这种情况很有效,但是当不是这种情况时,end将不正确。在以下情况下,如果变量page为3 end,则为1我该如何解决这个问题?

3 个答案:

答案 0 :(得分:7)

您可以使用Math.min

var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);

e.g。



var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 3;

var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);

console.log(`${start} to ${end} of ${totalItemsCount}`);




答案 1 :(得分:2)

您可以使用Math.min确保end不超过商品总数。
这是另一个对我来说更简单的解决方案:



function getPaginationText(totalItemsCount, numberOfItemsPerPage, page) {
  var pagesCount = (totalItemsCount - 1) / numberOfItemsPerPage + 1;
  var start = (page - 1) * numberOfItemsPerPage + 1;
  var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);

  return `${start} to ${end} of ${totalItemsCount}`;
}

console.log(getPaginationText(14, 5, 1));
console.log(getPaginationText(14, 5, 2));
console.log(getPaginationText(14, 5, 3));




如您所见,您不需要Math.floor,您可以使用整数除法。

答案 2 :(得分:1)

我建议使用稍微不同的方法来计算参数。



var pagination = (page, total, itemsOnPage) => {
        var numberOfPages = Math.ceil(total / itemsOnPage),
            start = (page - 1) * itemsOnPage + 1,
            end = Math.min(page * itemsOnPage, total);

        return `${start} to ${end} of ${total} on page ${page} of ${numberOfPages}`;
    };
   
console.log(pagination(1, 14, 5));
console.log(pagination(2, 14, 5));
console.log(pagination(3, 14, 5));
console.log(pagination(3, 15, 5));