This is the 27th day of my participation in The August More Wen Challenge.

Writing in the front

Everyday write code, will inevitably need to list rendering and other need to loop the scene, today we will review the JS statements used for loop it.

The body of the

For statement

The for statement is one of the most classic and versatile looping statements, and it’s very easy to use, and it has a lot of freedom, like output 0 to 100, we could write it like this.

for (let i = 0; i <= 100; i++) {
  console.log(i);
}
Copy the code

The for accepts three expressions, the first for the initial value, the second for the loop condition, and the third for the expression to be executed after the loop executes.

do… While statement

The do wilie statement differs from the for statement in that it is executed at least once and continues if the loop condition is met. An example of code that prints 0 to 100 is shown below.

let i = 0;
do {
  i += 1;
  console.log(i);
} while (i <= 100);
Copy the code

While statement

A while statement is more logical than a do while statement. A loop is executed only when the loop condition is met. This prevents the content from being judged more than once.

let i = 0;
while (i <= 100) {
  console.log(i++);
}
Copy the code

Break and continue statements

Of course, in a loop we may need to break out of the current body of the loop, or break out of the current body of the loop and proceed to the next loop, so we need these two statements.

  • Break Breaks the current loop body
  • Continue Breaks out of the current loop and continues with subsequent loops

So, if we have a for loop that starts at 0 and the loop condition is less than or equal to 100, how do we get it to output to 50 and not continue? In this case, break can be handled very well. The code is as follows.

for (let i = 0; i <= 100; i++) {
  if (i <= 50) {
      console.log(i);
  } else {
      break; }}Copy the code

Ok, so now if our requirement becomes, here we don’t print 50 to 60 between 0 and 100, then we need to continue, so we can write it like this.

for (let i = 0; i <= 100; i++) {
  if (i <= 50 || i >= 60) {
      console.log(i);
  } else {
      continue; }}Copy the code

conclusion

In this article we take a look at loops and iterations in JS, and how to break out of the current loop.

The front end is long and long. We are all on the road. We hope to communicate with our friends and make progress together. Keep updating ing…..