This section provides tutorial examples on how to use arrays and loops in VBScript language.
Array is a build-in data structure in Visual Basic language. It can used to store
a collection of data elements with indexes to access each element.
Arrays can be declared to hold a fixed number of elements as:
dim weekdays(5)
Arrays can also be declared to a variable number of elements as:
dim weekdays()
redim weekdays(5)
other statements
redim preserve weekdays(7)
Elements in a array can be iterated with the "for each ... next" statement as:
dim weekdays(5)
other statements
for each day in weekdays
other statements
next
Here is a simple ASP page to how the features of arrays:
<script language="vbscript" runat="server">
' array.asp
' Copyright (c) 2002 by Dr. Herong Yang
' This program demonstrates some special rules about arrays.
'
response.write("<html><body>")
response.write("<b>Tests on arrays</b>:<br/>")
dim days()
redim days(5)
' Referring elements by index
days(0) = "Mon"
days(1) = "Tue"
days(2) = "Wed"
days(3) = "Thu"
days(4) = "Fri"
' Iterating through indexes
for i=0 to 5-1
response.write("Element " & i+1 & " = " & days(i) & "<br/>")
next
' Increasing the size of the array
redim preserve days(7)
days(5) = "Sat"
days(6) = "Sun"
i = 1
response.write("Two days added:<br/>")
for each d in days
response.write("Element " & i & " = " & d & "<br/>")
i = i + 1
next
response.write("</body></html>")
</script>
Output
Tests on arrays:
Element 1 = Mon
Element 2 = Tue
Element 3 = Wed
Element 4 = Thu
Element 5 = Fri
Two days added:
Element 1 = Mon
Element 2 = Tue
Element 3 = Wed
Element 4 = Thu
Element 5 = Fri
Element 6 = Sat
Element 7 = Sun
Element 8 =
Note that:
Indexes of elements in arrays starts with 0.
"redim" can only be used against arrays that are declared with dynamic size.
"redim" can be used repeatedly.
"redim preserve" can be used to preserve the elements that already exist.
"for each ... next" statement revealed an extra element in the array. I am not sure
why?