I'm making a data pager, but I'm already stuck. I have two problems. I want it to jump from 10 to 10 elements and it does so from 20 to 20, I don't know why. I need to set a limit, that is, it does not bring me all from a given index, but only 10 from that index, or whatever is marked as the size of the page, but it continues to bring me everything.
I'm a bit confused array.slice
so here's an example of what I've done.
const arr = Array.from( Array( 100 ).keys() );
let currentPage = 0;
const pageSize = Number( document.getElementById('pagesize').value ) || 10;
const change = ( num ) => {
currentPage += num;
if( currentPage < 0 ) {
currentPage = 0;
} else if ( currentPage > Math.ceil( ( arr.length / pageSize ) ) ) {
currentPage = Math.ceil( ( arr.length / pageSize ) );
} else {
currentPage += num;
}
document.getElementById('result').innerHTML = arr.slice( ( pageSize * currentPage ) );
};
<input id="pagesize" value="10">
<button onClick="change(-1)">Menos</button>
<button onClick="change(1)">Más</button>
<div id="result"></div>
The error when using
array.slice
is that you are omitting to indicate thefin
.Solution:
Personally, I prefer to set my
currentPage
equal to the number that the user should see, that is, it would not start with0
but with1
It would also validate that
currentPage * pageSize
it does not exceed the length of the array.Finally, we would have to calculate
from
andto
( from and to ) and use them inslice
.Example:
The method
.slice()
is identical to.substring()
, that is, it extracts a string from index[start]
to index[end - 1]
. The parameter[end]
is optional and if omitted it extracts to the end.In this case you would be extracting your entire string because you only indicate the first value in a few words.
Now the reason for your error is that you add twice
currentPage += num
twice, once at the beginning of the function and the other in your if conditions in the last else, the conditions make your variable meet the condition and twice add num at the end of your operation so instead of multiplyingpageSize* currentPage
that should give you 10 as a result, it gives you 20 instead since currentPage at the end of the operation is worth 2.According to your conditionals the first if will never be executed because the value of
currenPage
is not less than zero at any time,currenPage
nor is it greater thanMath.ceil(arr.length/pageSize)
because this is equal to 10 and finally there is your condition ofcurrentPage += num
in your last condition which if execute.