The function of a loop statement is to repeatedly execute the same piece of code. Although it is divided into several different types, its principles are almost the same; as long as the given conditions are met, the statements contained in the loop body will be continuously executed and will be terminated once the conditions are no longer met.
While loop is a pre-test loop, which means that the conditional judgment of whether to terminate is before executing the code, so the body of the loop may not be executed at all. The syntax is as follows:
while(expression) statement
When expression is ture, the program will continue to execute statement statement until expression is false.
Two cases
The code copy is as follows:
<script type="text/javascript">
var i=iSum=0;
while(i <= 100){
iSum += i;
i++;
};
document.write(iSum+"<br>"); //Find the sum of numbers within 100
</script>
<p>Click the button below and keep looping on the code block as long as i is less than 5. </p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
While (i<=10)
{
x=x + "The number is " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script>