Wednesday 27 April 2011

VBScript & ASP: loops!

   


Everybody uses looping functions with VBScript, however do we know how many possible variant there are? How many statements? Ok, now close your eyes and count them. How many statements can you remember?

The looping statements are used to repeat a block of code for a predetermined number of times. There are 4 statements to do so:
1) For ... Next - the code is run a number of times;
2) For Each ... Next - the code is run for each item in a collection;
3) Do ... Loop - the code is run until a condition is met;
4) While ... Wend - the same as Do ... Loop.



For ... Next
As said, the statement is used to run a block of code a specified number of times. The For determines the starting and ending of the loop, while Next increments the variable (i) by one.
<%
For i = 0 to 5
   response.write ("Count: " & i & "<br>")
Next
%>
Using the Step keyword, we can determine the value by which the variable (i) is incremented. In the following example we increment it by 3:
<%
For i = 0 to 10 Step 3
   response.write ("Count: " & i & "<br>")
Next
%>
You can even use negative numbers for the Step keyword: remember though that the loop should be someway reversed:
<%
For i = 10 to 1 Step -1
   response.write ("Count: " & i & "<br>")
Next
%>
You can even use an Exit point in the looping:
<%
For i = 0 to 12
  if i = 5 then Exit For
  response.write ("Count: " & i & "<br>")
Next
%>

For Each ... Next
Using the For Each, lets you loop through a collection:
<%
Dim fruits(3)
fruits(0) = "Apples"
fruits(1) = "Bananas"
fruits(2) = "Oranges"
fruits(3) = "Pears"

For Each x in fruits
   response.write (x & "<br>")
Next
%>

Do ... Loop
If we don't know the number of loops, before running the statement, we can use the Do ... Loop. The code is run until a condition is met or while a condition is true.
With the While keyword, every time the loop is closed we check a condition.
<%
Do While i > 10
  some code
Loop
%>
The code inside the loop is executed only when i is greater than 10.
<%
Do
  some code
Loop While i > 10
%>
The code inside the loop is executed at least one time, even if i is less than 10.
If we use the Until keyword, the code is executed until a condition is met.
<%
Do Until i = 10
   some code
Loop
%>
The code is executed unless i is equal to 10.
<%
Do
  some code
Loop Until i = 10
%>
The code is executed at least one time, even if i is equal to 10.
We can exit the loop with Exit Do.
<%
Do Until i = 10
  i = i -1
    If i < 10 then Exit Do
Loop
%>
The code is executed until i is different from 10, and as long as i is greater than 10.

While ... Wend
The statement is used mainly in repeat region.
<%
While NOT RS.EOF
   some code
Wend
%>

And that is all. Hope you find this short article useful!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.