Below I have explained all the ways to initialize and use arrays in VBScript.
Every element of an array is associated with a unique index number. By default, index number starts from 0. The number of elements in an array is a fixed number. It can also be re-adjusted dynamically.
Arrays can have multiple dimensions-VBScript supports up to 60.
1)
Dim variable_name(upper_limit) [As data_type]
If “As data_type” is not specified, it will be a variant. Above we have declared a fixed size array. The array size limit is upper_limit +1 because index starts from 0.
2)
Dim variable_name() [As data_type]
ReDim [Preserve] variable_name(upper_limit)
Firstly we declare an array with no upper limit and then with redim we reset the upper bound to a new value. The optional key word "Preserve" states that all of the old elements must be preserved when changing the array size.
The size of the dynamic array changes during the time our script is running. The array is initially declared using either the Dim statement or using the ReDim statement. For a dynamic array, no size or number of dimensions is placed inside the parentheses.
Dim first_Array()
ReDim second_Array()
In the below example, ReDim sets the initial size of the dynamic array to 25
ReDim first_Array(25)we can resize a dynamic array unlimited number of times.
Dim array_dynamic()
' Size the dimension to contain one dimension with 3 elements
ReDim array_dynamic(2)
' Put data in the array
array_dynamic(0) = "1"array_dynamic(1) = "2"array_dynamic(2) = "3"
' Resize the array, but keep the existing dataReDim Preserve array_dynamic(5)' Display the 3rd elementMsgBox array_dynamic(2)MsgBox displays 3.3)variable_name = Array(element1, element2, ...)
Array function takes values of variant type and returns a dynamic sized array.
The arguments are a listing of values that will become the elements of the array.
dim a
a=Array(5,10,15,20)document.write(a(3))Output:20
Some of the Array keywords and their uses:
Keyword | Function |
---|---|
Dim | It will Declare an array |
Erase | Reinitializes the elements if it is a fixed-size array and deallocates the memory used if it is a dynamic array. |
IsArray | will Return True if A is an array, False if it is not |
LBound | will Return lower bound of an array, in VBScript it will always returns 0 |
Preserve | Preserve (Optional) is used to preserve the data in an existing array, when you resize it. |
ReDim | This is used to size or resize a dynamic array. |
UBound | will Return an upper bound of array |