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:
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 | |
---|---|
0 | Bananas |
1 | Bread |
2 | Pasta |
Creating Arrays in VBScript
VBScript arrays are created by first assigning an array object to a variable name...
then by assigning values to the array...
So, using our prior example, we could write:
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
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.
This results in:
Modify the Contents of an Array
You can modify the contents of an array by specifying a value for a given index number:
Now, the value of the second element will be: