VBScript arrays
Arrays are a very important concept in VBScript as well as many other languages. An array is a special type of variable which stores a set of related values.
This lesson focuses on:
- Creating an array
- Adding values to an array
- Accessing an arrays elements
- Modifying an arrays elements
Creating an array
An array is created the same way a regular variable is created, with the addition of the number of the elements in the array next to the array name in parenthesis.
Syntax for creating an array:
Dim arrayName(numElements)
Example:
<script type="text/vbscript"> Dim colors(4) </script>
In the above example, an array named "colors" that can store 4 elements is created.
Adding values to an array
Once you create an array, you can add values to it by specifying the array name, an index in the array and a value to be placed in that index.
Syntax:
arrayName(index) = value
Example:
<script type="text/vbscript">
Dim colors(4)
colors(0) = "green"
colors(1) = "blue"
colors(2) = "gray"
colors(3) = "orange"
</script>
In the above example, an array named "colors" that can store 4 elements is declared. Four values are added to it.
NOTE: The first index of an array is 0, not 1!
Accessing an arrays elements
To access an arrays elements, refer to the array with the appropriate index number in brackets.
NOTE: Array indexes start at 0. So the 1st element of an array would be at index 0, the 5th element of an array would be at index 4, and so on.
Example:
<script type="text/vbscript">
Dim colors(4)
colors(0) = "green"
colors(1) = "blue"
colors(2) = "gray"
colors(3) = "orange"
'print the last element of the colors array
document.write("The last element in the colors array is "
& colors(3))
</script>
Output:
Modifying an arrays elements
To modify an arrays elements, refer to the array with the appropriate index number in brackets of the value you want to change and set it to the new value.
Example:
<script type="text/javascript">
Dim colors(4)
colors(0) = "green"
colors(1) = "blue"
colors(2) = "gray"
colors(3) = "orange"
document.write("The old value of colors(1): " & colors(1))
document.write("
The old value of colors(3): "
& colors(3))
'change the value of colors(1)
colors(1) = "teal"
'change the value of colors(3)
colors(3) = "violet"
document.write("
The new value of colors(1): "
& colors(1))
document.write("
The new value of colors(3): "
& colors(3))
</script>
Output:
The old value of colors(3): orange
The new value of colors(1): teal
The new value of colors(3): violet




