VBScript: Array Functions - Multi-Dimensional Arrays
(Page 3 of 6 )
In VBScript you can create arrays with up to sixty dimensions. You'll probably never need to, but you know there is some nerd out there trying to pick up chicks by bragging about how he once created a 60 dimensional array that held every ancillary character from the Phantom Menace. I mean there are those people that build log cabins out of toothpicks to ensure they are remembered after passing over to the dark abyss.
It's far easier to show you how to use multidimensional arrays than to explain them, and since I am a lazy writer, that is exactly what I am going to do:
<html>
<body>
<script type="text/vbscript">
Dim cow(3,2)
cow(0,0) = "Mister Moo "
cow(0,1) = "Moo McGoo "
cow(0,2) = "Bessie "
cow(0,3) = "Elmer"
</script>
</body>
</html>
In the above example we create a multidimensional array, specifically, a two-dimensional one. You will notice that cow(3,2) has two numbers separated by a comma. This is because multidimensional arrays work similar to a grid or a spreadsheet, with the first number representing a row and the second number representing a column. So for instance, in the above code, Bessie appears in row 0 of column 2. You perform actions on multidimensional arrays the same as you would any other array.
Dynamic Arrays
Dynamic arrays are arrays whose size can be altered. To do so, you first initialize the array with no elements, then use ReDim to change its size, like so:
<html>
<body>
<script type="text/vbscript">
Dim cow()
Redim cow(2)
cow(0)="Moo"
cow(1)="Moo Moo"
cow(2)="Moo Moo Moo"
Redim Preserve cow(3)
cow(3)="Moo Moo Moo Moo"
</script>
</body>
</html>
The above code initially creates a dynamic array named cow, with no elements. We then use ReDim to change the number of elements within cow to 3 (cow(2)). Then we add some values to the array. Finally, we decide to add even more elements to cow, and ReDim it again to hold 4 values. We add the fourth value to the array, making sure to use the Preserve keyword. Had we not used Preserve, then all of the data in our array would have been deleted when we Redimmed it.
Next: Array Functions >>
More Windows Scripting Articles
More By James Payne