If you've used VBScript's arrays before, you're likely aware that you can dynamically resize
arrays using the Redim
statement. (To learn more, see the
technical documentation
for Redim
.) Sometimes this can be a pain, though. For example, imagine that you wanted to read
each line of a text file into an array. Since you do not know the number of lines in the file initially,
there is no way to create a preset array size. Rather, you would use code like:
|
While this is feasible, you, the developer, have to Redim
the array at each iteration.
Now, imagine that you wanted to delete a particular element from the array and then compact the array?
Ugh. This would involve moving elements backwards through the array then issuing another Redim
statement to compact the array.
What would be nice would be to have an easy-to-use dynamic array class. This class would have the same functionality of a regular array, but would be dynamic in nature. That is, the developer working with this class could simply say:
|
and not have to worry if the array MyArray
was of the proper dimensions or not. Also, it would be
nice if the developer could easily delete an element from the array and compact it with code like:
|
If you are new to classes, I highly recommend you read some of the great articles on VBScript classes before continuing on with this article:
The DynamicArray
Class
This class needs only one member variable, the actual array that is used to store the data (named aData
).
In the Initialize
event, aData
is Redim
ed as an array with one element.
Note that arrays are indexed starting at zero, not one, in this class.
The class contains two Property Get
statements: Data
and DataArray
.
Data
returns a particular array element while DataArray
returns the entire array.
A single Property Let
statement exists for the Data
property. This array does the
grunt work of Redim
ing the array, if needed.
The DynamicArray
class contains three methods: StartIndex
, StopIndex
, and
Delete
. StartIndex
simply returns the starting array index (like LBound
)
while StopIndex
returns the array's current greatest possible index (like UBound
).
The third and final method, Delete
, removes a particular element from the array and then compacts
the array.
In Part 2 we'll look at how to use this array to create truly dynamic
arrays. The remainder of this part contains the source code for the DynamicArray
class.
|