定义一个简单的数组
有两种方法在asp中定义数组,让我们看看每种的例子:
方法一:
MyArray = Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct", "Nov","Dec")
方法二:
Dim myArray(2)
myArray(0)="Jan"
myArray(1)="Feb"
动态改变数组的大小
DIM myArray()
REDIM myArray(20) '将数组重新定义为20维
可扩展数组举例:将数组从0扩展到10
Dim MyArray()
for i = 0 to 10
ReDim Preserve MyArray(i) ‘Preserve 保留原来数据
MyArray(i)=...
next
.................................................................................................
有用的数组函数
Ubound(arrayName)函数
Lbound(arrayName)这个函数是返回数组的上标,也就是数组第一个元素的标记。
.................................................................................................
.................................................................................................
向另一个页面传递数组
现在有很多种方法向另一页面传递数组,目前有三种方法:
定义一个又逗号分隔的字符串,然后再下一页中用Split函数重新建立数组。
将数组存储在一个Session变量中,然后在下一个页面中调用。
通过表单的隐含区域来传递数组,他们都是自动用逗号分开,然后再用Split函数重新建立数组。
前两种方法很好,但是都比第三中复杂。在这里我们将只介绍第三种,因为它是最简单最有效的。
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>
以上我们做的是在一个表单中用单独的隐含域存储数组中的每个元素,我们再看看下一页:
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>
------------------------------------------------
将一个字符串分割并返回分割结果的数组
Dim MyArray
MyArray = Split(tempcnt,chr(13)&chr(10))
For I = Lbound(MyArray) to Ubound(MyArray)
Response.Write MyArray(I) & "<br>"
Next
数组排序函数
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..
数组排序函数应用例子
Dim MyArray
MyArray = Array(1,5,123,12,98)
MyArray = Sort(MyArray)
For I = Lbound(MyArray) to Ubound(MyArray)
Response.Write MyArray(I) & "<br>"
Next
在Application和Session中使用数组
Application.Lock
Application("StoredArray") = MyArray
Application.Unlock
LocalArray = Application("StoredArray")
覆盖Application中的数组
Application.Lock
Application("StoredArray") = LocalArray
Application.Unlock
Session使用方法与Application相同
从数据库中把数据导入数组中
Dim MyArray
取出全部记录
MyArray = RS.GetRows
取出前10项记录
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