Replacing an index with a string

Asked

Viewed 41 times

1

I’m listing on the screen numbers of 1 à 15 and checking that the number is divisible by 3 and for 5 adding a text when true, until then it works, but, only that still displays the number below the text, how do I exchange the number for the text. I’ve used the replace unsuccessful:

var nums = $(".nums");
	
  for(var i=1; i<16; i++) {

     if(i % 3 == 0) {
         var tres = i;
         tres = "Divisível por 3";
         nums.append(tres+"<br>");
     } else if(i % 5 == 0) {
         var cinco = i;
         cinco = "Divisível por 5";
         nums.append(cinco+"<br>");
     }

  nums.append(i+"<br>");

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="nums"></div>

1 answer

3


If you store in an array you will have more flexibility to handle/precess the data the way you want, in this case include a separator <br> among the elements

var nums = [];
for(var i=1; i<16; i++) {

    if(i % 3 == 0 && i % 5 == 0)
        nums.push(i+ " é divisível por 3 e por 5");
    else if(i % 3 == 0)
        nums.push(i+ " é divisível por 3");
    else if(i % 5 == 0) 
        nums.push(i+ " é divisível por 5");
    else
        nums.push(i);

}
$(".nums").append(nums.join('<br>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="nums"></div>

  • 1

    Top Miguel, Putz, really hadn’t thought about storing in an array. Thank you very much man!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.