JS 遍历请求分页
效果图
递归方式
const pageSize = 10 ;
function paginateData ( page, pageSize ) {
return new Promise ( ( resolve, reject ) => {
setTimeout ( ( ) => {
const data = Array. from ( { length : pageSize } , ( _, i ) => ` Item ${ page * pageSize + i } ` ) ;
resolve ( data) ;
} , 1000 ) ;
} ) ;
}
function traversePageData ( page = 0 ) {
paginateData ( page, pageSize) . then ( data => {
console. log ( 'res:' , data) ;
if ( data. length === pageSize) {
traversePageData ( page + 1 ) ;
} else {
console. log ( '已遍历完所有数据。' ) ;
}
} ) . catch ( error => {
console. error ( '请求分页数据时发生错误:' , error) ;
} ) ;
}
traversePageData ( ) ;
for循环
const list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ;
const pageSize = 10 ;
function paginateData ( array, page_size ) {
let pageCount = Math. ceil ( array. length / page_size) ;
for ( let i = 0 ; i < pageCount; i++ ) {
let page = array. slice ( i * page_size, ( i + 1 ) * page_size) ;
console. log ( ` Page ${ i + 1 } : ${ page } ` ) ;
}
}
paginateData ( list, pageSize) ;