简体   繁体   English

如何将我的数组分成 discord.js 中的一些部分?

[英]How to separate my array into some parts in discord.js?

I'm doing pagination in an embed and I wanted to split 4 elements from an array for each page.我在嵌入中进行分页,我想为每个页面从一个数组中拆分 4 个元素。 How do I do this?我该怎么做呢? (to update when I click the button). (当我点击按钮时更新)。 Until then I have only the first step which is to get the first 4 elements, from the first page, with:在那之前,我只有第一步,即从第一页获取前 4 个元素,其中:

.slice(0, 4)

How do I get the next 4, and the next, and so on...我如何获得下一个 4,下一个等等......

you need to define:你需要定义:

  • currentPage variable (set to 1 as default value) currentPage 变量(设置为 1 作为默认值)
  • pageSize - how many items should be for one page pageSize - 一页应该有多少项目
  • countPages - for calculation, rounded in bigger side countPages - 用于计算,在大边四舍五入

I have written 3 methods我写了3个方法

  • loadFirstPage()
  • loadNextPage()
  • loadPrevPage()

 const input = [1,2,3,4,5,6,7,8,9,10,11,12,13]; let currentPage = 1; let pageSize = 4; const countPages = Math.ceil(input.length / pageSize); function loadFirstPage() { currentPage = 1; return [...input].splice(0, pageSize) } function loadNextPage() { const nextPage = currentPage + 1; if (nextPage <= countPages) { currentPage = nextPage; const startIndex = currentPage * pageSize - pageSize; return [...input].splice(startIndex, pageSize) } else { currentPage = countPages; const startIndex = currentPage * pageSize - pageSize; return [...input].splice(startIndex, pageSize) } } function loadPrevPage() { const prevPage = currentPage - 1; if (prevPage >= 1) { currentPage = prevPage; const startIndex = currentPage * pageSize - pageSize; return [...input].splice(startIndex, pageSize) } else { currentPage = 1; const startIndex = currentPage * pageSize - pageSize; return [...input].splice(startIndex, pageSize) } } console.log('output data: ', loadFirstPage(), 'current page: ', currentPage); console.log('output data: ', loadNextPage(), 'current page: ', currentPage); console.log('output data: ', loadNextPage(), 'current page: ', currentPage); console.log('output data: ', loadNextPage(), 'current page: ', currentPage); console.log('output data: ', loadNextPage(), 'current page: ', currentPage); console.log('output data: ', loadPrevPage(), 'current page: ', currentPage); console.log('output data: ', loadPrevPage(), 'current page: ', currentPage); console.log('output data: ', loadPrevPage(), 'current page: ', currentPage); console.log('output data: ', loadPrevPage(), 'current page: ', currentPage);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM