JS basic grammar --- do-while loop + summary of the while loop and do-while loop

1. summarize: while loops and do-while loop

 

  • while loop characteristics: first judgment, after the loop , it is possible to execute a loop not   

 

  • do-while loop characteristics: first cycle, the determination , at least once loop
 
Contrast experience:
 
1. do-while loop characteristics: first cycle, the determination, at least once loop
      var i = 0;
      do {
        console.log ( "Aniehasi eh Yo!");
        i++;
      } while (i < 1);

 

2. while loop characteristics : first determine, after cycle, it is possible once the loop is not executed
      where i = 5;
      while (i < 4) {
        console.log ( "Little Su Shuaio good");
        i++;
      }
      console.log ( "quack.");

 

 

2. do-while loop

    

  grammar:

     do{
         Loop
     } While (condition);

 

    

 Implementation process:

First time through the loop body, and then determine whether the conditions established,

It does not hold, out of the loop

The establishment of the iteration of the loop, and then determine whether the conditions are fulfilled, so the loop continues, otherwise jump .....

 

Exercise 1: Output: Haha, I become handsome ..10 times

      var i = 0;
      do {
        console.log ( "ha ha, I become handsome");
        i++;
      } while (i < 10);

 

Exercise 2:

Q. users: You think I'm handsome it prompts the user to enter y / n, if n has been asked, if the user input y, the end, and prompts the user, your good taste?
      do {
        var result = prompt ( "Do you think I'm handsome do y / n?");
      } while (result != "y");
      console.log ( "Do you really visionary");

 

Exercise 3: Find all within 100 and a multiple of 3

 

Implemented a while loop:

      var i = 1;
      was some = 0;
      while (i <= 100) {
        if (i % 3 == 0) {
          sum += i;
        }
        i++;
      }
      console.log(sum); //1683

 

Cycle implemented with do-while:
      var i = 1;
      was some = 0;
      do {
        if (i % 3 == 0) {
          sum += i;
        }
        i++;
      } while (i <= 100);
      console.log(sum);

 

 

 

Guess you like

Origin www.cnblogs.com/jane-panyiyun/p/11913047.html