JavaScript Tutorial/Statement/while

Материал из Web эксперт
Перейти к: навигация, поиск

Check the loop counter for while loop

   <source lang="javascript">

<html> <head> <title></title> </head> <body> <script type="text/javascript"> var i = 1; while (i < 101) {

   if (i == 99) {
       alert("The number is " + i);
   }
   i++;

} </script> </body> </html></source>


Nesting If statement to a while statement

   <source lang="javascript">

<html> <head> <title>Number Guesser</title> <script> var guess = 50; var target = 0; var turns = 0; var msg = ""; target = Math.floor(Math.random() * 100) + 1; guess = eval(prompt("What is your guess?", guess)); while (guess != target){

 turns++;
 if (guess > target){
   guess = eval(prompt (turns + ".  Too high!! Next guess?", guess));
 }
 if (guess < target){
   guess = prompt (turns + ".  Too low!! Next guess?", guess);
 }
 if (guess == target){
   msg = "YOU WIN!!! \n";
   msg += "It took you ";
   msg += turns + " turns! ";
   alert (msg);
 }

} </script> </head></source>


Use Do while loop to reverse a string

   <source lang="javascript">

<HTML>

  <BODY>

<SCRIPT> var newString = ""; var theString = "abcde"; var counter = theString.length; do { newString += theString.substring(counter-1, counter); counter--; } while (counter > 0 ); document.write(theString + " reversed is " + newString + "!"); </SCRIPT>

  </BODY>

</HTML></source>


Use integer variable to control the while loop

   <source lang="javascript">

<html> <head> <title>A Simple Page</title> <script language="JavaScript">

</script> </head> <body> </body> </html></source>


Use while loop to output all elements in an array

   <source lang="javascript">

<html> <head> <title>Use while loop to output all elements in an array</title> </head> <body>

Use while loop to output all elements in an array

<script language="javascript" type="text/javascript">

</script> </body> </html></source>


Using While loop to check user input

   <source lang="javascript">

<html> <head> <title>Using While loop to check user input</title> <script> var correct = "AA"; var guess = ""; while (guess != correct){

 guess = prompt ("Question?", "");
 if (guess == correct){
   alert ("Correct");
 } else {
   alert ("that"s not it...");
 }

} </script> </head> <body> </body> </html></source>


while loop

The while loop can be summarized as while the expression evaluates to true, execute the statements in the loop.

Once the last statement in the loop is executed, go back to the top of the loop and evaluate the expression again.

When the expression evaluates to false, the next line of code following the while loop structure is executed.

Because the expression is evaluated before the loop, it is possible the loop will never be executed.

The format of the while loop looks like the following:



   <source lang="javascript">

while (expression)

   {
     statement;
   }</source>