如何使用 javascript 在页面更改期间确定索引

How to determine the index during page change using javascript

提问人:learntocode2468 提问时间:6/20/2023 最后编辑:learntocode2468 更新时间:6/20/2023 访问量:44

问:

我总共有 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

)}




JavaScript 数组循环 对象 索引

评论

1赞 trincot 6/20/2023
请附上您拥有的与此问题相关的代码。
0赞 Hedi Zitouni 6/20/2023
你能提供你试图得到这个结果的代码吗?
0赞 learntocode2468 6/20/2023
@HediZitouni,我已经更新了尝试过的问题
0赞 learntocode2468 6/20/2023
@trincot更新了问题,包括我尝试过的内容
0赞 Hedi Zitouni 6/20/2023
您的代码是节点可用的。但我的理解是,索引应该等于:“3*pageIndex+i+1”而不是“++i”。我无法告诉您如何使用您提供的代码获取 pageIndex。此外,在这种情况下,请避免使用 ++i,而更喜欢 i+1。您可能会有不良的副作用

答:

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))