Stop counting for Jquery

Asked

Viewed 42 times

0

How can I stop the FOR count in Jquery? For example:

That code:

for (i = 0; i < 5; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}

Will show the result:

The number is 0
The number is 1
The number is 2
The number is 4

But I would like to display 5 results and not 4. How do I make FOR not increment ++? I’ve tried it this way:

for (i = 0; i < 5; i++) {
  if (i === 3) { i--; continue; }
  text += "The number is " + i + "<br>";
}

But for some reason it crashes the screen and on the server gives error 503 which means it is consuming a lot of processing.

  • Play a break instead of continue

  • Your server is Node?

  • If I break him into the loop for good, then we’ll only have the result until "The number is 2"

  • It’s not Node Leonardo

  • From an example of how the result you hope to obtain.

  • What is the server? pq javascript does not cause 503 on the server, it is processed in the browser.

  • The break will cause it to stop completely the for... it will not pass to the next repeat, will exit and continue the flow of the code.

Show 2 more comments

2 answers

3


What is happening is that your code is looping, since when you have i=3 you decrease it and the continue makes it go to the next loop of the for, where it becomes worth 3 again, and so goes into loop.
An alternative would be to do the for run into the i be less than or equal to 5:

for (i = 0; i <= 5; i++) { //alterado
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}
  • Interesting remark from Lucas.

  • Thank you very much Lucas. Exactly that! It worked perfectly.

1

Another way to do what you want is to count the amount of elements you have already written on the screen. Although being a little more extensive is more generic and will work even if you want to ignore several elements.

Example:

let text = "";

for (let i = 0, escritos = 0; escritos < 5; i++) { //variavel escritos termina em 5
    if (i === 3) { continue; }
    text += "The number is " + i + "<br>";
    escritos++; //conta apenas os que foram escritos na tela
}

document.write(text);

So the stop value does not depend on calculations you have to do to know where to end the for, and becomes the amount you want to show on the screen.

Imagine you wanted to show 15 elements and jump each multiple of 3:

let text = "";

for (let i = 0, escritos = 0; escritos < 15; i++) {
    if (i % 3 === 0) { continue; }
    text += "The number is " + i + "<br>";
    escritos++;
}

document.write(text);

Note that in both cases I declared the variable i in the for, which is something that I had not done and can cause problems, because it turns global. Always declare the variables you use.

Browser other questions tagged

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