提问人:learntocode2468 提问时间:6/20/2023 最后编辑:learntocode2468 更新时间:6/20/2023 访问量:44
如何使用 javascript 在页面更改期间确定索引
How to determine the index during page change using javascript
问:
我总共有 13 条记录,每页大小为 3。
记录在对象数组中,并将其显示在有效的卡片中。record
第 1 页记录将有响应 3 条记录,
第 2 页记录将有响应另外 3 条记录
...第 N 页
对于每张卡,我都显示记录索引
在页面上,卡片会像
page 1;
card1->
index 1 // written code as ++i
card2->
index 2
card3->
index 3
Expected behaviour for page 2
page 2;
card1->
index 4 // should continue
card2->
index 5
card3->
index 6
当前对于 page2 am 返回索引为
wrong behaviour
page 2;
card1->
index 1 {++i} does not work for 2 second page still treated as index from 0
card2->
index 2
card3->
index 3
试
// for page 1, i get as
var records = [
{id: 21, color: "red"},
{id: 32, color: "blue"},
{id: 52, color: "green"}
]
// for page 2, i get as
var records = [
{id: 21, color: "brown"},
{id: 42, color: "indigo"},
{id: 22, color: "yellow"}
]
// also i retreive total records as well
[
{id: 21, color: "red"},
{id: 32, color: "blue"},
{id: 52, color: "green"},
{id: 21, color: "brown"},
{id: 42, color: "indigo"},
{id: 22, color: "yellow"}
]
displaying as
{records.map((e, i)=>
<div>Card {++i}</div>
<div>Index {++i}</div> // this value on page2 should not repeat same index
)}
答:
0赞
imvain2
6/20/2023
#1
看起来你真的只是在尝试对数组进行分页。因此,您可以使用 array.slice 来获取所需的数组部分。我的回答是,您只需传递结果数组、每页要显示的数字和当前页面。
const results = [
{id: 21, color: "red"},
{id: 32, color: "blue"},
{id: 52, color: "green"},
{id: 21, color: "brown"},
{id: 42, color: "indigo"},
{id: 22, color: "yellow"}
];
const getResults = (arry, perPage, page) => {
const start = page * perPage - perPage;
const end = start + perPage;
return arry.slice(start, end);
};
console.log(getResults(results, 3, 1))
console.log(getResults(results, 3, 2))
评论