在循环迭代特定次数后添加一个按钮。

huangapple go评论71阅读模式
英文:

Add a button after a loop has iterated a specific number of times

问题

我已创建了3个变量:

let first_product = 0;
let second_product = 20;
let page_number = 1;

然后,我通过一个数组进行了循环:

for (let i of myArray) {
    // 执行操作
}

一旦for循环遍历了20个项目,我想要在新页面上显示接下来的20个项目。我使用以下代码来实现这一点:

let paginated_products = products.slice(first_product, second_product);

for (let i of myArray) {
    // 执行操作

    if (i === second_product) {
        let button = document.createElement('button');
        button.innerHTML = page_number;
        page_number += 1;
        document.getElementById('nav-buttons').appendChild(button);
        first_product += 20;
        second_product += 20;
    }
}

然而,按钮没有显示。

如果我去掉if条件,每次循环迭代运行时都会创建一个新按钮。

如何才能使按钮仅在循环运行到second_product值的迭代时显示(即在迭代20、40、60等时)?

英文:

I have created 3 variables:

let first_product = 0;
let second_product = 20;
let page_number = 1;

I have then looped through an Array:

for (let i of myArray) {
    // Perform actions
}

Once the for loop has looped through 20 items, I want to display the next 20 items onto a new page. I have done this using the following code:

let paginated_products = products.slice(first_product, second_product);

for (let i of myArray) {
    // Perform Actions

    if (i === second_product) {
        let button = document.createElement('button');
        button.innerHTML = page_number;
        page_number += 1;
        document.getElementById('nav-buttons').appendChild(button);
        first_product += 20;
        second_product += 20;
    }
}

However, the buttons are not displayed.

If I remove the if condition, a new button is created each time a loop iteration is run.

How could I cause a buttons to be shown only when the loop is running the iteration of the value second_product (when the loop is at iteration 20, 40, 60 etc).

答案1

得分: 0

如果你有一个名为 products 的数组,并且需要确定当前正在迭代的产品属于哪一页,你只需进行数学计算:

const pageNumber = Math.floor(iProduct / productsPerPage) + 1;

而要确定何时转到下一页,仍然在迭代过程中,你可以使用取模运算符进行计算:

if (iProduct % productsPerPage === 0) {

在这个演示中,我展示了如何迭代 products 数组并呈现相应页面的按钮:

英文:

If you have an array of products and you need to determine to which page belongs the current product you are iterating, you need to just do the math:

const pageNumber = Math.floor(iProduct / productsPerPage)+1;  

And to determine when the page turns to the next, still while iterating, you can still do the math using the modulo operator:

if(iProduct % productsPerPage == 0){

Here in this demo I show how to iterate over the products array and render the buttons for the correspondent page:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

//builds the products array with 100 objects
const products =
  ((n)=&gt;{
    const a = [];
    for(let i=1;i&lt;=n;i++){ a.push({cod:i}); }
    return a;
  })(100);

processProducts(products, 20);

/**
 * Loops through all the passed products and renders the buttons for each page
 */
function processProducts(products, productsPerPage){
  //for each single product in products
  iProduct = 0;
  for (let product of products) {  
  
    //[perform Actions on the current product]
  
    //here I determine which page the current product belongs to  
    const pageNumber = Math.floor(iProduct / productsPerPage)+1;  

    //if the current product is the first of its page
    if(iProduct % productsPerPage == 0){
      //render a button for the correspondent page
      let button = document.createElement(&#39;button&#39;);
      button.innerHTML = pageNumber;
      document.getElementById(&#39;nav-buttons&#39;).appendChild(button);         
    }      

    //increment the product index
    iProduct++;
  }
}

<!-- language: lang-html -->

&lt;div id=&quot;nav-buttons&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

答案2

得分: 0

以下是您要翻译的内容:

One possible approach was to write a function which does create an array of array-chunks from any provided array and provided chunk size. Creating chunks is based on the modulo/remainder (%) operator and e.g a reduce task.

The following steps then would be ...

  • Creating an array of product batches from the products array by passing it to the chunks creating function.

  • Iterating the array of product batches via e.g. forEach where the index parameter of the callback function equals the page number value less 1 (hence index is zero based).

While iterating the product batches one ...

  • should take care of the rendering of the pagination buttons.
  • could take care of each product item of the currently processed batch.
function chunkArray(arr, chunkCount) {
  return arr.reduce((list, item, idx) => {
    if (idx % chunkCount === 0) {
      list.push([item]);
    } else {
      list[list.length - 1].push(item);
    }
    return list;
  }, []);
}

const products = Array
  .from({ length: 14 }, (_, idx) => `product_${idx + 1}`);

const productBatches = chunkArray(products, 5);

console.log({
  products,
  productBatches,
});

function createPaginationButton(pageNumber) {
  let elm = document.createElement('button');
  elm.textContent = pageNumber;
  document.querySelector('#nav-buttons').appendChild(elm);
}

productBatches
  // - process each product batch.
  .forEach((batch, batchIndex) => {

    // - for example create a paginated
    //   list of products per batch.

    batch.forEach((product, productIndex) => {
      // - do whatever needs to be done
      //   with/to each product item.
    });

    createPaginationButton(batchIndex + 1);
  });
<div id="nav-buttons"></div>
英文:

One possible approach was to write a function which does create an array of array-chunks from any provided array and provided chunk size. Creating chunks is based on the modulo/remainder (%) operator and e.g a reduce task.

The following steps then would be ...

  • Creating an array of product batches from the products array by passing it to the chunks creating function.

  • Iterating the array of product batches via e.g. forEach where the index parameter of the callback function equals the page number value less 1 (hence index is zero based).

    While iterating the product batches one ...

    • should take care of the rendering of the pagination buttons.
    • could take care of each product item of the currently processed batch.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function chunkArray(arr, chunkCount) {
  return arr.reduce((list, item, idx) =&gt; {
    if (idx % chunkCount === 0) {

      list.push([ item ]);
    } else {
      // list.at(-1).push(item);
      list[list.length - 1].push(item);
    }
    return list;
  }, []);
}

const products = Array
  .from({ length: 14 }, (_, idx) =&gt; `product_${ idx + 1 }`);

const productBatches = chunkArray(products, 5);

console.log({
  products,
  productBatches,
});

function createPaginationButton(pageNumber) {
  let elm = document.createElement(&#39;button&#39;);
  elm.textContent = pageNumber;
  document.querySelector(&#39;#nav-buttons&#39;).appendChild(elm);
}
productBatches
  // - process each product batch.
  .forEach((batch, batchIndex) =&gt; {

    // - for example create a paginated
    //   list of products per batch.

    batch.forEach((product, productIndex) =&gt; {
      // - do whatever needs to be done
      //   with/to each product item.
    });

    createPaginationButton(batchIndex + 1);
  });

<!-- language: lang-html -->

&lt;div id=&quot;nav-buttons&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 18:50:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定