VBScript Arrays

A VBScript array is a special type of variable that allows you to store multiple values against a single variable.

For example, say you have a shopping list that you want to store and write out to the screen. You could store these in a simple variable like this:

Copy to Clipboard
item1 = "Bananas"
item2 = "Bread"
item3 = "Pasta"

This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do things like, loop through all your variables. If these values were stored in an array, you could save yourself a lot of time.

What Does an Array Look Like?

Arrays can be visualized as a stack of elements. Each element has an index number (left column) and a value (right column).

Note that VBScript arrays start their numbering at zero.

Array
0Bananas
1Bread
2Pasta

Creating Arrays in VBScript

VBScript arrays are created by first assigning an array object to a variable name...

Copy to Clipboard
Dim arrayName(numberOfElements)

then by assigning values to the array...

Copy to Clipboard
arrayName(0) = "Array element 1"
arrayName(1) = "Array element 2"
arrayName(2) = "Array element 3"

So, using our prior example, we could write:

Copy to Clipboard
Dim shoppingList(3)
shoppingList(0) = "Bananas"
shoppingList(1) = "Bread"
shoppingList(2) = "Pasta"

Accessing Array Data

You can access data in an array by referring to the name of the array and the element's index number.

Display a Single Array Element

This example displays the second element of the array named shoppingList (remember that VBScript array index numbers begin at zero). In this case, the value would be Bread

Copy to Clipboard
document.write(shoppingList(1))

So, building on our previous example, you could use the following code to declare an array, assign values, then output the contents to the screen.

Copy to Clipboard
Dim shoppingList(3)
shoppingList(0) = "Bananas"
shoppingList(1) = "Bread"
shoppingList(2) = "Pasta"
document.write(shoppingList(1))

This results in:

Bread

Modify the Contents of an Array

You can modify the contents of an array by specifying a value for a given index number:

Copy to Clipboard
shoppingList(1) = "Wholemeal Bread"

Now, the value of the second element will be:

Wholemeal Bread

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!

Sponsored Link: Design CODE-FREE Websites

Check a Domain:

ZappyHost Logo