Dynamic Arrays – VBScript

There are two types of arrays:

  1. Static arrays
  2. Dynamic arrays

Static array has to be declared with the number of elements that the array can hold (i.e. arr(5)).  If we don’t know the number of elements to be stored in the array, then the dynamic array can be used.

Syntax:

Dim arr()

ReDim keyword should be then used to declare the number of elements that the array can hold.

Syntax:

Dim arr()

ReDim arr(5)

Example:

Dim arr()

ReDim arr(5)
    arr(0)=10
    arr(1)=15
    arr(2)=20
    arr(3)=25
    arr(4)=30
    arr(5)=35

msg=""

For i=0 to 5
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next

msgbox msg

ReDim arr(6)
arr(6)=40

msg=""

For i=0 to 6
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next

msgbox msg

In the above example, array is initially sized with five elements.  Array elements with indices 0 to 5 are initialized and displayed using for loop.  The array is resized with ReDim keyword and then the added array element is initialized with the statement “arr(6)=40”.

Let us execute the script and have a look at the output.

Output before resizing the array:

dynamicarray1

Output after resizing the array:

dynamicarray2

If we see both of these images, definitely a question pops up in our mind.  Why in the second output Arr(0) to Arr(5) are blank? Why Arr(6) is only having a value.

To overcome this problem, we need to use Preserve keyword

We will use the Preserve keyword with the ReDim in the above example.

Dim arr()

ReDim arr(5)
    arr(0)=10
    arr(1)=15
    arr(2)=20
    arr(3)=25
    arr(4)=30
    arr(5)=35

msg=""

For i=0 to 5
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next

msgbox msg

ReDim Preserve arr(6)
arr(6)=40

msg=""

For i=0 to 6
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next

msgbox msg

Let us execute the new script with Preserve keyword and see the output.

preserve

Output shows the array element values starting from Arr(0) to Arr(6).  Preserve keyword preserves the values of the array elements before ReDim statement.  Hence, if we resize the array with ReDim and add new elements does not erase the earlier values of the array.

Follow the steps below to use the dynamic arrays:

  1. Declare the array with no size – Dim array_name()
  2. Re-declare the size of the array with ReDim & Preserve – ReDim Preserve array_name(number of elements)

Example:

Dim arr()

ReDim arr(5)

{assign values}

ReDim Preserve arr(10)

Comments 22

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.