VBScript Tutorials - Herong's Tutorial Examples - v6.03, by Herong Yang
"Dim x()" - Dynamic-Size Array Example
This section provides a tutorial example on how to declare a dynamic-size array 'Dim x()'. 'ReDim x(n)' statement must be used on to set the size of a dynamic-size array before it can be used.
We learned from previous sections that a dynamic-size array must be declared with a no size. For example, "Dim x()" declares a dynamic-size array, x, with no upper bound limit. You must set the size of x with a statement like "ReDim x(99)" before you can use it.
One important nature of a dynamic-size array is that it can be re-sized with a "ReDim Preserve x(n)" statement. The keyword "Preserve" is important, if you want to keep all old values in the array.
To show you how a dynamic-size array works, I wrote the following example, array_dynamic_size.html:
<html>
<body>
<!-- array_dynamic_size.html
- Copyright (c) 1998 HerongYang.com. All Rights Reserved.
-->
<pre>
<script language="vbscript">
document.writeln("")
Dim aYear()
document.writeln("Check 1: Is aYear an array? " & IsArray(aYear))
' aYear(0) = "Jan" 'Error 1: Subscription out of range
' iSize = UBound(aYear)+1 'Error 2: Index out of range
ReDim aYear(5)
document.writeln("Check 2: Is aYear an array? " & IsArray(aYear))
aYear(0) = "Jan"
aYear(1) = "Feb"
aYear(5) = "Jun"
ReDim Preserve aYear(11)
aYear(10) = "Nov"
document.writeln("Months in a year:")
For i=LBound(aYear) To UBound(aYear)
document.writeln(" " & i & " = " & aYear(i))
Next
</script>
</pre>
</body>
</html>
Here is the output:
Check 1: Is aYear an array? True Check 2: Is aYear an array? True Months in a year: 0 = Jan 1 = Feb 2 = 3 = 4 = 5 = Jun 6 = 7 = 8 = 9 = 10 = Nov 11 =
Note that:
Table of Contents
Introduction of VBScript - Visual Basic Scripting Edition
Variant Data Type, Subtypes, and Literals
Numeric Comparison Operations and Logical Operations
String Operations - Concatenation and Comparison
Variable Declaration and Assignment Statement
Expression and Order of Operation Precedence
Statement Syntax and Statement Types
►Array Data Type and Related Statements
"Dim x()" - Declaring Array Variables
"x(i)" - Accessing Array Elements with Indexes
"Dim x(n)" - Fixed-Size Array Example
►"Dim x()" - Dynamic-Size Array Example
"Erase" Statement - Removing All Elements in an Array
Data Type "Variant()" - Array of Variant Values
Array References and Array Assignment Statements
Conditional Statements - "If ... Then" and "Select Case"
Loop Statements - "For", "While", and "Do"
"Function" and "Sub" Procedures
Inspecting Variables Received in Procedures
Error Handling Flag and the "Err" Object
Regular Expression Pattern Match and Replacement
scrrun.dll - Scripting Runtime DLL Library
IE Web Browser Supporting VBScript