需求:

写个函数pagination,接收两个参数,第一个是总数,第一个是当前页码,要求当前页码尽可能的在正中间,最多显示5个页码。
比如 pagination(10,4) 就输出 2 3 4 5 6
pagination(10,2)就输出 1 2 3 4 5
pagination(3,1)就输出 1 2 3

function pagination(total, current = total) {
  if (current > total) current = total;
  if (current < 1) current = 1;
  var res = [current];
  var num = 4,
    step = 0,
    prev = false,
    next = false;
  var i = (j = current);
  while (step < num) {
    if (step < num && j++ < total) {
      step++;
      res.push(j);
    } else {
      next = true;
    }
    if (step < num && i-- > 1) {
      step++;
      res.unshift(i);
    } else {
      prev = true;
    }
    if (prev && next) {
      break;
    }
  }
  return res;
}

体验更好的是在页面很多的情况下中间的用< <或者>>
代码如下

export const pagination = (totalNum = 5, needEllipsis = true) => (
  total,
  current = total,
) => {
  if (current > total) current = total;
  if (current < 1) current = 1;
  const res = [current];
  totalNum--;
  let step = 0,
    prev = false,
    next = false;
  let i = current;
  let j = current;
  while (step < totalNum) {
    if (step < totalNum && j++ < total) {
      step++;
      res.push(j);
    } else {
      next = true;
    }
    if (step < totalNum && i-- > 1) {
      step++;
      res.unshift(i);
    } else {
      prev = true;
    }
    if (prev && next) {
      break;
    }
  }
  if (needEllipsis) {
    if (res[0] !== 1) {
      if (res[0] - 1 > 1) {
        res.unshift('<<');
      }
      res.unshift(1);
    }
    if (res[res.length - 1] !== total) {
      if (total - res[res.length - 1] > 1) {
        res.push('>>');
      }
      res.push(total);
    }
  }
  return res;
};
分类: Web前端

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据