思路分析:
page的落点只有三种情况。
情况1:page落在左侧特殊区;
情况2:page落在右侧特殊区;
情况3:page落在中间区域。
3种情况分别处理一下即可。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 创建分页组件需要的 按钮数组
// btnCount: 最多能看到几个按钮
// total: 总条数
// size: 每页几条
// page: 当前第几页
function f(total, size, page, btnCount = 5) {
// show me your code
const maxPage = Math.ceil(total / size)
const gap = Math.floor(((btnCount - 1) / 2)) //如果btnCount是偶数,则page靠左侧。
const arr = [] // 能看到的页码集合
// 1. page位于左侧禁区
if((page=>1) && (page <= gap)){
for(let i=0; i< btnCount; i++) {
arr.push(i+1)
}
console.log(arr)
return arr
}
// 2. page位于右侧禁区
if(page<=maxPage && page>= (maxPage -gap)){
for(let i=0; i<btnCount; i++) {
arr.push(maxPage-btnCount+i+1)
}
console.log(arr)
return arr
}
// 3. page位于安全区
for(let i = 0; i<btnCount; i++) {
arr.push(page-gap+i)
}
console.log(arr)
return arr
}
// 在可能的情况下,让page处于正中间
f(100, 10, 1, 5) // ==> [1, 2, 3, 4, 5]
f(100, 10, 7, 5) // ==> [5, 6, 7, 8, 9]
f(100, 10, 2, 5) // ==> [1, 2, 3, 4, 5]
f(100, 10, 5, 5) // ==> [3, 4, 5, 6, 7]
f(101, 10, 8, 3) // ==> [7, 8, 9]
f(101, 10, 10, 5) // ==> [7, 8, 9, 10, 11]
</script>
</body>
</html>