The do-while statement [duplicate]
Possible Duplicate:
When is a do-while appropriate?
Would someone mind telling me what the difference between these two statements are and when one should be used over the other?
var counterOne = -1;
do {
counterOne++;
document.write(counterOne);
} while(counterOne < 10);
Or:
var counterTwo = -1;
while(counterTwo < 10) {
counterTwo++;
document.write(counterTwo);
}
http://fiddle.jshell.net/Shaz/g6JS4/
At this moment in time I don't see 开发者_Python百科the point of the do
statement if it can just be done without specifying it inside the while
statement.
Do / While VS While is a matter of when the condition is checked.
A while loop checks the condition, then executes the loop. A Do/While executes the loop and then checks the conditions.
For example, if the counterTwo
variable was 10 or greater, then do/while loop would execute once, while your normal while loop would not execute the loop.
The do-while
is guaranteed to run at least once. While the while
loop may not run at all.
do while
checks the conditional after the block is run. while
checks the conditional before it is run. This is usually used in situations where the code is always run at least once.
The do statement normally ensures your code gets executed at least once (expression evaluated at the end), whilst while evaluates at the start.
Lets say you wanted to process the block inside the loop at least once, regardless of the condition.
if you would get the counterTwo value as a return value of another function, you would safe in the first case an if statement.
e.g.
var counterTwo = something.length;
while(counterTwo > 0) {
counterTwo--;
document.write(something.get(counterTwo));
}
or
var counterTwo = something.length;
if(counterTwo < 0) return;
do
{
counterTwo--;
document.write(something.get(counterTwo));
} while(counterTwo > 0);
the first case is useful, if you process the data in an existing array. the second case is useful, if you "gather" the data:
do
{
a = getdata();
list.push(a);
} while(a != "i'm the last item");
精彩评论