Arrays¶
An array is a series of values held in a single variable.
Declaration¶
An array is declared in a similar way to variables, except that an array uses parenthesis to define a set number of values.
Below, the size of the array is stated in brackets:
Using Dim¶
Specifying the Size¶
Using 'Array' Parameter Dim arr3¶
- An array can always hold one more value than specified, as the array starts at ZERO which is not included in the count.
- The size cannot be negative.
- A single array variable can hold multiple types of value, e.g. an integer, string or character.
Assigning Values to an Array¶
In order to assign values to an array, an array index value is added alongside each value of the array.
Example
Dim arr(5)
arr(0) = "1" 'Number as String
arr(1) = "VBScript" 'String
arr(2) = 100 'Number
arr(3) = 2.45 'Decimal Number
arr(4) = #10/07/2013# 'Date arr(5) = #12.45 PM# 'Time
- Value stored in Array index 0 : 1
- Value stored in Array index 1 : VBScript
- Value stored in Array index 2 : 100
- Value stored in Array index 3 : 2.45
- Value stored in Array index 4 : 7/10/2013
- Value stored in Array index 5 : 12:45:00 PM
Multi Dimension Arrays¶
A VBScript array can have a maximum of 60 dimensions. Two-dimension arrays are the most common, however.
Example
In the below example, a multi-dimension array is declared with 3 rows and 4 columns.
Dim arr(2,3) ' Which has 3 rows and 4 columns arr(0,0) = "Apple" arr(0,1) = "Orange"
arr(0,2) = "Grapes"
arr(0,3) = "pineapple"
arr(1,0) = "cucumber"
arr(1,1) = "beans"
arr(1,2) = "carrot"
arr(1,3) = "tomato"
arr(2,0) = "potato"
arr(2,1) = "sandwitch"
arr(2,2) = "coffee"
arr(2,3) = "nuts"
When the above code is saved as .HTML and executed in Internet Explorer, it produces the following result:
- Value stored in Array index : 0 , 1 : Orange
- Value stored in Array index : 2 , 2 : coffee
Redim Statement¶
The ReDim and ReDim Preserve Statements are used to resize previously declared arrays.
ReDim¶
Redim resizes an array. Any previous values in the array will be cleared.
ReDim Preserve¶
Redim Preserve resizes an array but any existing values of the array will be maintained.
If the resized array is larger the new elements are added to the end of the array with an empty value.
If the resized array is smaller the last elements will be removed i.e. their values are lost.
Dim MyArray(3) As Integer ' Declare dynamic array.
MyArray(0) = 1
MyArray(1) = 2
MyArray(2) = 3
Redim Preserve MyArray(5) ' Allocate 5 elements - keep the values of the first three elements
Example
In the below example, an array has been redefined and then preserved the values when the existing size of the array is changed.
Note : Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost.