JavaScript while loop writing

 The usage of JavaScript while loop is actually quite similar to the usage of PHP while loop. When the condition is met, the while loop will execute a piece of code until the condition is not met. It is often used to display search results or directory listings. Place, please see the following example.


JavaScript while loop example
<script language="javascript">
var i=0;
while( i<10) {
 document.write(i);
 i++;
}
</script>
Output result: 0123456789

We set a while loop, when i is less than 10, the loop will be executed, and the first line of the while loop content, document.write(i) means to output the value of the variable i, output After executing i++, the variable i will be +1, so the final output result is continuous from zero to nine.

There is another variation of the JavaScript while loop. It is executed first and then the condition is judged. It is generally called do...while loop

JavaScript do...while loop example
<script language="javascript">
var i=0;
do {
 document.write(i);
 i++;
}while( i<10 );
</script>
The output result is the same as the first example, because we give the same conditions, but reverse the execution of the while loop and the judgment mode, so the result will be the same, whether it is using the while loop or rewriting it to do...while It’s okay, as long as it can meet the results that the web page is going to present at the time.

Post a Comment

0 Comments