<%
' 创建示例二维数组(数组的数组结构)
Dim students
students = Array( _
Array("001", "张三", 20), _
Array("002", "李四", 22), _
Array("003", "王五", 21) _
)
' 创建字典对象
Set dict = Server.CreateObject("Scripting.Dictionary")
' 遍历二维数组,将学号作为键,姓名和年龄作为值存入字典
For i = 0 To UBound(students)
Dim currentRow, key, value
currentRow = students(i) ' 获取当前行数据
key = currentRow(0) ' 学号作为键
value = Array(currentRow(1), currentRow(2)) ' 姓名和年龄作为值
dict.Add key, value ' 添加到字典
Next
' 示例:通过学号检索学生信息
Dim searchKey, studentInfo
searchKey = "001"
If dict.Exists(searchKey) Then
studentInfo = dict(searchKey)
Response.Write "学号 " & searchKey & " 的信息:<br>"
Response.Write "姓名:" & studentInfo(0) & "<br>"
Response.Write "年龄:" & studentInfo(1)
Else
Response.Write "学号 " & searchKey & " 不存在。"
End If
' 释放对象
Set dict = Nothing
%>
代码说明:
二维数组定义
使用 Array 嵌套创建二维数组 students,每行包含学号、姓名、年龄。
创建字典对象Set dict = Server.CreateObject("Scripting.Dictionary") 实例化字典。
遍历数组并填充字典
循环遍历二维数组的每一行。
提取每行的学号作为键(currentRow(0))。
将姓名和年龄组成新数组作为值。
使用 dict.Add key, value 将键值对加入字典。
检索数据
使用 dict.Exists(key) 检查键是否存在。
通过 dict(key) 获取值,并访问数组元素。
注意事项:
键唯一性:确保作为键的列(如学号)唯一,否则 Add 方法会报错。可用 Exists 方法提前检查。
数组索引:VBScript 数组默认从 0 开始索引。
比较模式:默认区分大小写,可通过 dict.CompareMode = vbTextCompare 设为不区分大小写(需在添加键前设置)。