Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - For loop a number to create buttons inside template literal

Getting a bit stuck with this one.

I'm looping through an object (dataLayer.Tests) and I'm displaying the values of my content, in a DIV. Here's an example of how this object looks:

enter image description here

I'm doing this by looping through my object with forEach. (And in this example, I'm just console.logging my result result3).

The problem I'm having, is that within my forEach, I want to display create/display buttons, depending on what the number is in the totalVariants key/value.

So for example, if the totalVariants === 2, I want to create 2 buttons. If it is one, I want to create 1 button.

I know I need to for loop through this particular value, but I'm not sure how to do this, within a template literal.

Here's my code.

dataLayer.Tests.forEach((element, index, array) => {
      let result3 = '';

      let numberOfVariants = element.totalVariants;

      if (numberOfVariants >= 1) {

        for (i = 0; i < numberOfVariants; i++) {
          console.log("The number is ", i + 1);
        }

        result3 += `
        <div class="CRO-variant-result">
          <p>Date Launched: ${element.date}</p>
          <p>Test ID: ${element.id}</p>
          <p>Test Description: ${element.name}</p>
          <p>Variant Active: ${element.variant}</p>
          <p>Total Variants: ${element.totalVariants}</p>

          ${(function () {
            for (i = 0; i < element.totalVariants; i++) {
              return `<button>${i}</button>`
            }
        })()} 
        </div>
       `
       console.log("result3", result3);

      };
    });

I've seen solutions which include .map and object.keys, but this doesn't seem to work/return anything. (Probably as I just need to loop through a number and not array etc.

Any ideas/pointers, would be appreciated.

Basically, I'm not sure how to loop through a number, within a template literal and return x number of elements.

Thanks, Reena


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

numberOfVariants is an number, not an object, so one way you could do this is create a new incrementing array of that length (Array.from(Array(numberOfVariants).keys()) does this nicely) and then map over that array as you're doing.

${Array.from(Array(numberOfVariants).keys()).map(i => (
  `<button value="${i}">${i}</button>`
)).join('')}

I'm not quite sure what you want to appear inside the button (maybe the integer of the current number as you increment)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...