javascript 计算总页数的分页逻辑
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46108128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pagination logic in calculating total of pages
提问by Cecilia Chan
I'm using a react component that need me to pass in below prop
我正在使用一个需要我在下面传递的反应组件
<Pager
totalPages={10}
currentPage={1}
/>
I can't figure out the calculation as in the api I have total_items, not totalPages. if I have 50 total_items, how can I produce 5 for the totalPagesprop? says my limit is 10.
我无法弄清楚我拥有的 api 中的计算total_items,而不是totalPages. 如果我有 50 total_items,我如何为totalPages道具生产 5 ?说我的限制是 10。
回答by fubar
Divide total_itemsby limit, and round the value up.
分total_items通过limit,并且轮价值高达。
Math.ceil(total_items/limit);
50 items / 10 per page = 5 pages
55 items / 10 per page = 6 pages
回答by Ashraf
you need to check if there is a quotient from the divide operation because there is apparently few items need to be showed in another page
您需要检查除法运算是否存在商数,因为显然其他页面中需要显示的项目很少
for example:
例如:
6 items
5 limit
if we just divide and ceilwe will get 1which is incorrect because there is one item need an extra page to be counted
如果我们只是divide and ceil我们会得到1,这是不正确的,因为有一个项目需要计算额外的页面
totalPages_pre = (total_items/limit)
totalPages = (search.total % page_size) == 0 ? totalPages_pre : totalPages_pre + 1

