An array is a collection of ordered data. The elements in the array may not belong to the same data type. Use a unified array name and subscript to uniquely identify the elements in the array. Changing one element will not affect other elements. The subscripts of arrays are bounded and are divided into lower bounds and upper bounds. Arrays can be declared using Dim, Private, Public or Static, and their syntax formats are the same. The following only introduces the method of using Dim to declare an array.
1. Array definition and declaration
The definition syntax of an array is as follows:
Dim array name ([[lower bound of subscript To] upper bound of subscript]) [As data type]
For example (assuming that the default lower bound for arrays in the current module is 0)):
① Dim A(10) As Integer
Indicates that the array name is A. The lower bound of the subscript of this array is the default value 0, and the upper bound of the subscript is 10. There are 11 elements of Integer type, from A(0), A(1) to A(10).
② Dim B(1 To 20) As Integer
Indicates that the array name is B. The lower bound of the subscript of this array is 1, the upper bound of the subscript is 20, and there are 20 elements of type Integer, from B(1) to B(20).
③Dim DayArray(50)
Indicates that DayArray is a Variant array with 51 indexed (from 0 to 50) elements.
④Dim Matrix(3, 4) As Integer
Indicates that Matrix is a two-dimensional Integer array.
⑤Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double
Indicates that MyMatrix is a three-dimensional double array with explicitly specified upper and lower bounds.
⑥Dim Birthday(1 To 10) As Date
Indicates that BirthdayDay is a Date type array with indexes from 1 to 10.
2. Option Base statement
The Option Base statement is used at the module level to declare a default lower bound for array subscripts.
The syntax of the Option Base statement is as follows:
Option Base {0 | 1}
Note: By default, the lower bound of the array is 0, and there is no need to use the Option Base statement at this time. If you use this statement to specify an array lower bound of 1, you must use the Option Base statement before the module's array declaration.
Notice:
(1) The To clause in Dim, Private, Public, ReDim and Static statements provides a more flexible way to control the subscript of the array. However, if you do not specify a lower bound explicitly using the To clause, you can use Option Base to set the default lower bound to 1. The lower bound of an array created using the Array function is also determined by the lower bound specified by the Option Base statement, unless the Array is qualified by a type library (such as VBA.Array) name. If it is qualified by a type library name, then the lower bound of the array created using the Array function is The lower bound is not affected by Option Base.
(1) The Option Base statement only affects the lower bound of the array located in the module containing the statement.
A few notes on array declarations:
①The naming rules for array names are the same as those for variable names.
② The array name is enclosed in parentheses, square brackets cannot be used, unlike C language.
③The lower bound of the subscript must not be greater than its upper bound.
④ You can use variable names or constant names (as well as real numbers) as subscript boundaries. When the boundary of the subscript is a constant name, the size of the array is fixed. When the boundary of the subscript is a variable name, the size of the array can be dynamically defined, that is, the size of the array depends on the value of the variable during the running of the program. Therefore, arrays in VB can be divided into two types of arrays: static arrays and dynamic arrays.
3. static array
A static array means that the number of array elements is fixed, that is, the size of the memory space they occupy is fixed. According to the different dimensions of fixed-size arrays, it can be divided into one-dimensional arrays and multi-dimensional arrays.
The syntax format for declaring a multidimensional array is:
Dim array name ([subscript boundary list]) [As data type]
The definition form of subscript boundary: [subscript lower bound To] subscript upper bound
The subscript boundary list refers to the subscript boundaries of each dimension of the array separated by commas, that is
[Subscript lower bound To] Subscript upper bound, [Subscript lower bound To] Subscript upper bound, ..., [Subscript lower bound To] Subscript upper bound
(first dimension) (second dimension) (nth dimension)
When n=1, the array is called a one-dimensional array; when n=2, the array is called a two-dimensional array; and so on, when n=m, the array is called an m-dimensional array.
The following examples introduce the use of one-dimensional arrays.
'Declare a string array FriendsName with a length of 51
Dim FriendsName(50) As String
'Declare a global integer array Class of length 11
Public Class(10) As Integer
The number of elements in a one-dimensional array is (upper bound - lower bound + 1).
You can use a loop statement to assign an initial value to an array, such as:
Dim I As Integer
For I = 0 To 11 'Use program flow control of loop statements
C(I) = I
Next I
If a lower bound is not specified explicitly, the lower bound of the array is controlled by the Option Base statement. If there is no Option Base statement, the lower bound defaults to 0.
The dimension of the array is not limited to 2. In VB, it can be expanded to 60. In practical applications, there are not many applications for arrays with more than three dimensions. When defining a multidimensional array, you only need one Dim statement to specify all subscript boundaries of the array. Using multidimensional arrays can easily represent some meaningful statistical data. For example:
Dim Profit(16,10,12) As Currency
This Profit array can be used to represent the profit of a certain department store with store name, department and month as parameters. For example: Profit(2,8,11) represents the profit of the eighth department of the second branch in November.
4. dynamic array
Sometimes it is not possible to know how large an array is needed to meet actual needs before the array is started to be used. Of course, the size of the array can be defined to be large enough to meet any practical application needs, but this method is very inefficient (a large waste of memory space). If you use a dynamic array, you can accurately define the size of the array according to actual needs while the program is running.
When declaring an array, not giving a list of dimensions declares the array as a dynamic array. For example:
Dim MyArry() As Integer
Before using a dynamic array, you must use the ReDim statement to redefine it. For example, the array MyArry declared earlier can be defined as a dynamic two-dimensional array using the following statement.
ReDim MyArry(10,10)
You can also define dynamic arrays multiple times by repeatedly executing the ReDim statement. The maximum number of dimensions that can be defined using ReDim is 60. The ReDim statement can change the number of elements in each dimension of the array, but not the number of dimensions. The following is an example of a standard application of the ReDim statement.
Dim MyArry() As Single 'Declare a dynamic array
ReDim MyArry(30,20,10) 'Redefine the array
ReDim MyArry(50,23,21) 'Redefine the array again
The syntax of ReDim is the same as that of Dim. In addition, it also has the option Preserve keyword:
ReDim Preserve array name ([ [lower bound To] upper bound]) [As data type]
For example:
ReDim MyArry(50,23,21)
ReDim Preserve MyArry(50,23,50)
Note: When using ReDim, redefining the array will cause the values of all array elements to disappear, while using Preserve can retain the data. But using Preserve can only preserve the data of the array when changing the size of the last dimension of the array. For one-dimensional arrays, all data will be retained, but for multi-dimensional arrays: only the size of the last dimension can be changed to retain all array data, otherwise an error will occur.
5. LBound function and UBound function
Both the LBound function and the Ubound function return a Long type data. The value obtained by the former is the minimum subscript available for the specified array dimension, while the value obtained by the latter is the maximum subscript. Their syntax is:
LBound(array name[, specified dimension])
UBound(array name[, specified dimension])
The array name is required. The specified number of dimensions is optional and specifies which dimension to return the lower bound for. 1 represents the first dimension, 2 represents the second dimension, and so on. If the specified dimension is omitted, it defaults to 1.
For how to use the LBound function and the UBound function, see the following example:
Dim A(1 to 100,3,-3 to 4) As Integer 'Define a three-dimensional array, assuming that the Option Base language is not used
' statement changes the default value of the array lower bound.
Use the Lbound and Ubound functions on array A. The return value list is as follows
The default lower bounds for all dimensions depend on the setting of the Option Base statement. It can be seen that using the LBound function and UBound function on an array can be used to determine the number of elements in an array.
For arrays whose dimensions are specified using a To clause in their declaration, they can use any integer as a lower bound without being restricted by the Option Base statement.
6. Advanced features of arrays
Although arrays are most commonly used to store groups of variables, arrays are useful in other ways. You can assign the contents of one array to another, create functions that return arrays, and you can create properties that return arrays. In many cases, these techniques can improve application performance.
Just as you can assign the value of one variable to another variable, such as StrA = StrB, you can also assign the contents of one array to another array. For example, you want to copy a byte array from one location to another. This can be achieved by copying one byte at a time. The procedure is as follows:
Sub ByteCopy(oldCopy() As Byte, newCopy() As Byte)
'The parameter oldCopy() is the source array, newCopy() is the target array
Dim i As Integer
ReDim newCopy (Lbound(oldCopy) To UBound(oldCopy)) 'Redefine dynamic array
For i = Lbound(oldCopy) To Ubound(oldCopy) 'Loop assignment
newCopy(i) = oldCopy(i)
Next
End Sub
A simpler and more efficient way is to directly assign one array to another array:
Sub ByteCopy(oldCopy() As Byte, newCopy() As Byte)
'The parameter oldCopy() is the source array, newCopy() is the target array
newCopy = oldCopy 'Use the array to assign values directly
End Sub
There are some rules to keep in mind regarding variable assignment. For example, although a variable declared as an integer can be assigned to a variable declared as a long without any problems, assigning a long to an integer variable can easily lead to an overflow error. In addition to complying with the rules regarding assignments between data type variables, array assignments must also comply with other rules, including the number of array dimensions, the size of each dimension, and whether the array is fixed or dynamic.
① Several factors to consider when assigning arrays with different dimensions and data types
l The array type on the left side of the assignment operator: fixed array (Dim x(1 to 10) As Integer) or dynamic array (Dim x() As Integer).
l Whether the dimension of the array on the left side of the assignment operator matches the dimension of the array on the right side of the assignment operator.
l Whether the number of array elements in each dimension of the arrays on both sides of the assignment operator matches. Dimensions may match even if the declaration of the arrays is different. For example, if the elements of each dimension of one array are numbered starting from 0 and the elements of another array are numbered starting from 1, the dimensions may also match.
l The data types of all elements on both sides of the assignment operator must be compatible. These rules are consistent with the rules for variable assignment.
Table 3-6 shows the impact of these factors:
Errors in array assignment may occur at compile time or at runtime (for example, if the data type cannot be cast or the assignment attempts to re-declare (ReDim) a static array). Design your program to add error handling to ensure that arrays match before assignment.
②Write a function that returns an array
It is possible to return a set of values from a function. For example, returning a set of bytes from a function without having to convert it to a string and back again.
Here's a simple example using a function that returns a byte array:
Private Sub Form_Load()
Dim b As Byte
Dim i As Integer
Dim ReturnArray() As Byte
b = Cbyte(54)
ReturnArray() = ArrayFunction(b) 'Call function
For i = Lbound(ReturnArray) To Ubound(ReturnArray)
Msgbox ReturnArray(i) 'Loop through the pop-up message box to display the array value
Next
End Sub
Public Function ArrayFunction(b As Byte) As Byte()
Dim x(2) As Byte
x(0) = b
x(1) = b + CByte(200)
x(2) = b + b
ArrayFunction = x 'returns the result as array x
End Function
After running the above example, ReturnArray() is a three-element array containing the values assigned to the array in the ArrayFunction. The ArrayFunction statement passes an array as a parameter; the array's data type must be the same as the function's data type (bytes in this case). Because this is a function call, parentheses are not necessary when passing the array.
Notice:
1. Although it is possible to return an array by assigning to another array (ArrayFunction = x()), this approach is not recommended for performance reasons.
2. A type must be specified for the function that returns an array. This type can be Variant. This way, Function X() As Variant() is valid and Function X() As () will fail.
3. When calling a function that returns an array, the variable used to store the return value must also be an array, and its data type must be the same as the function's return type, otherwise a type mismatch error will be displayed.
Define a simple array
There are two ways to define and initialize arrays in asp, let's see an example of each:
Method one:
MyArray = Array(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct, Nov,Dec)
The size of the array is determined by the number of initialized elements.
Method two:
Dim myArray(2) 'Specify the array size
myArray(0)=Jan
myArray(1)=Feb
Array dynamic expansion
DIM myArray()
REDIM myArray(20) 'Redefine the array size to 20
ReDim Preserve MyArray(i) 'Preserve retains the original data in the array
two-dimensional array
Example:
dim MyArray(5,10) 'defines a two-dimensional array
Example of two-dimensional assignment:
MYArray(3,3)=100
There is also a disguised implementation method for two-dimensional arrays:
dimMyArray(5)
MyArray(0)=Array(...) 'One-dimensional array
MyArray(1)=Array(...)'One-dimensional array
...
When accessing, use the format MyArray(x)(y)
array index
Use the above method to define an array. The subscript of the first element of each dimension array is 0, and the subscript of the last element is the number of elements -1.
But you can also specify the subscript of the array, such as:
dim MyArray1(3 to 10) 'The subscript is from 3 to 10, MyArray(3) gets the value of the first element
Useful array functions
Ubound(array name) function--returns the subscript of the last element of the array.
Lbound (array name) function--returns the subscript of the first element of the array, the default is 0.
More applications:
Array sort function
function Sort(ary)
KeepChecking = TRUE
Do Until KeepChecking = FALSE
KeepChecking = FALSE
For I = 0 to UBound(ary)
If I = UBound(ary) Then Exit For
If ary(I) > ary(I+1) Then
FirstValue = ary(I)
SecondValue = ary(I+1)
ary(I) = SecondValue
ary(I+1) = FirstValue
KeepChecking = TRUE
End If
Next
Loop
Sort = ary
End function
Array sorting function application example
DimMyArray
MyArray = Array(1,5,123,12,98)
MyArray = Sort(MyArray)
For I = Lbound(MyArray) to Ubound(MyArray)
Response.Write MyArray(I) & <br>
Next
Split a string and return an array
DimMyArray
MyArray = Split(string, separator)
For I = Lbound(MyArray) to Ubound(MyArray)
Response.Write MyArray(I) & <br>
Next
Using arrays in Application and Session
Application.Lock
Application(StoredArray) = MyArray
Application.Unlock
LocalArray = Application(StoredArray)
Overwrite array in Application
Application.Lock
Application(StoredArray) = LocalArray
Application.Unlock
Session usage is the same as Application
Import data from database into array
DimMyArray
Get all records
MyArray = RS.GetRows
Get the first 10 records
MyArray = RS.GetRows(10)
For row = 0 To UBound(MyArray, 2)
For col = 0 To UBound(MyArray, 1)
Response.Write (col, row) & <br>
Next
Next
Pass array to another page
There are many ways to pass an array to another page, such as the following three:
1. Define a comma-separated string, and then use the Split function to re-create the array on the next page.
2. Store the array in a Session variable and then call it on the next page.
3. Pass the array through the hidden area of the form. They are automatically separated by commas, and then use the Split function to re-create the array.
The first two methods are good, but both are more complicated than the third. Here we will only introduce the third one because it is the simplest.
File 1.asp:
<%
dim I
dim myArray(20)
for I=0 to 20
myArray(I)=Item & I
next
%>
<html>
<body>
<form name=testform method=post action=2.asp>
<%
for I=0 to ubound(myArray)
response.write <input type=hidden name=myArray value=' & myArray(I) & '>
next
%>
<p>
<input type=submit>
</form>
</body>
</html>
What we did above is to use a separate implicit field to store each element in the array in a form. Let's look at the next page:
File 2.asp
<html>
<body>
<%
dim arrString
dim myArray
dim I
arrString=request(myArray)
myArray = split(arrString,,)
for I=0 to ubound(myArray)
response.write Item &I& = & myArray(I) & <br> & vbCrLf
next
%>
</body>
</html>