Calculating item offset for pagination

前端 未结 9 2089
眼角桃花
眼角桃花 2020-12-12 20:53

this seems like very simple maths but somehow, my brain cant think ...

i am trying to implement pagination and will need to calculate the item offset to use in limi

相关标签:
9条回答
  • 2020-12-12 21:17

    Using JS as an example, for progressive web app people...

    JS arrays have the prototype method .slice(start, end) overview here it takes a start index and an end index as arguments.

    I found the easiest way to calc both indexes is as follows;

    Start Index

    var start =  parseInt((selectedPage - 1) * resultsPerPage);
    

    End Index

    var end = parseInt(selectedPage * resultsPerPage);
    

    Execution

    var myPaginatedArray.slice(start, end);
    
    0 讨论(0)
  • 2020-12-12 21:21

    Use offset = (page - 1) * itemsPerPage + 1.

    0 讨论(0)
  • 2020-12-12 21:21

    Honestly depends. I'm no PHP person, but I'll put both out there. If you are pulling your records in to some form of collection (list, array, etc.) then your formula should be:

    offset = (page - 1) * itemsPerPage
    

    This is because most (again, I'm not a PHP person) arrays and lists use 0 for their first element. If they do not use 0 for their first element and/or you're pulling from a table or something else where the IDs start at 1, then it should be:

    offset = (page - 1) * itemsPerPage + 1
    

    I hope that's clear and helps.

    0 讨论(0)
提交回复
热议问题