动态生成以5为一组进行的值

  • 本文关键字:一组 动态 javascript
  • 更新时间 :
  • 英文 :


我正在使用以下逻辑进行分页:

if (currentPage > 5 && currentPage < 11) pages = [6, 7, 8, 9, 10];
if (currentPage > 10 && currentPage < 16) pages = [11, 12, 13, 14, 15];
if (currentPage > 15 && currentPage < 21) pages = [16, 17, 18, 19, 20];
if (currentPage > 20 && currentPage < 26) pages = [21, 22, 23, 24, 25];

然而,与其硬编码这些值,我更愿意尽可能地写一个动态版本。如果您注意到,每个页面上总是有五个可单击的页码,由pages数组中的值表示。但我不清楚如何做到这一点。

  1. currentPage除以5
  2. value四舍五入,然后减去1。这一点很重要,因为在代码片段中,要在结尾保留5的倍数。
  3. 创建一个包含5个项目的数组,从(value * 5) + 1开始,并增加数组的长度。

function createPageRange(currentPage) {
const startingPageMultiple = Math.ceil(currentPage / 5) - 1;
const startingPage = (startingPageMultiple * 5) + 1;
return Array(5).fill().map((_, i) => i + startingPage);
}
console.log('currentPage = 1', createPageRange(1));
console.log('currentPage = 5', createPageRange(5));
console.log('currentPage = 6', createPageRange(6));
console.log('currentPage = 18', createPageRange(18));
console.log('currentPage = 21', createPageRange(21));

currentPage = 5;
pages = [];
pages = setPages(currentPage);
function setPages(num) {
begin = (currentPage%5)*5+6;
pages.length=0;
for (let i=0; i<5; i++) {
pages.push(begin++);
}
return pages;
}
console.log(pages);
currentPage = 11;
pages = setPages(currentPage);
console.log(pages)

最新更新