Home > Articles

  • Print
  • + Share This

Arrays and Loops

An array is a group of variables that share the same name. Each member of the group is called an element. You declare an array as you would a variable except that you add an index number within a set of parentheses in order to indicate how many elements are within the array. For example, to declare an array named Stooges that contains three elements, you write

Dim Stooges(2)

Usually, the first element of an array has the index number zero. Thus, the second element has the index number one and so on. This is why the array declared previously has an index of two, yet contains three elements. The code in Listing 3.6 shows you how to create the array, Stooges, assign a string as each element, and then display the output in an HTML Input element of type=text. You'll notice that a For...Next loop is used to create the text output. We'll cover For...Next loops in a moment.

LBound and UBound functions

You use the LBound function to determine the lowest bound element of an array. You use the UBound function to determine the upper bound element of an array. The syntax is

For example, in an array MyArray(4)
LBound(MyArray) returns 0
UBound(MyArray) returns 4

Listing 3.6: Using an Array in Script (03asp06.htm)

  Sub button1_OnClick()
    Dim Stooges(2)
    Dim i
    Dim OutStr

    Stooges(0) = "Moe"
    Stooges(1) = "Larry"
    Stooges(2) = "Curly"
    For i = 0 to UBound(Stooges)
      OutStr = OutStr + ": " + Stooges(i)
      text1.value = OutStr
  End Sub

Figure 3.5 displays the output of the script shown in Listing 3.6.

Figure 3.5 When you use client-side script, you can output data to the HTML text Input element.

Notice that in Listing 3.5 a For...Next loop is used to traverse an array. VBScript supports the looping statements that you find in standard Visual Basic. Table 3.1 shows you the standard looping statements available to you in VBScript.

Table 3.1: VBScript Looping Statements




For i = 0 to 5

r = 10 + i



While i <= 5

i = i + 1




i = i + 1

Loop Until i > 5

For...Next loops in VBScript

When using a For...Next loop in VBScript please be aware that you do not need to include the counter variable in the Next statement as you do in standard Visual Basic.

Visual Basic For...Next Loop

For i = 0 to 10
  r = 10 + i
Next i

VBScript For...Next Loop

For i = 0 to 10
  r = 10 + i
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.