在ASP中,普通数组无法直接实现键值对操作,但可以通过结构重组模拟类似效果。以下是使用数组模拟字典结构的实现方法:
<% ' 初始化results主数组 Dim results() ReDim results(-1) ' 初始为空数组 ' 创建父节点结构(用数组模拟字典) Dim parentDict(1) parentDict(0) = "children" ' 键名 parentDict(1) = Array() ' 值初始化为空数组 ' 创建子节点结构(用数组模拟字典) Dim childDict(2) childDict(0) = "key1" childDict(1) = "value1" childDict(2) = "otherData" ' 将子节点添加到父节点的children集合 Dim tempChildren tempChildren = parentDict(1) ' 获取当前children数组 ReDim Preserve tempChildren(UBound(tempChildren) + 1) tempChildren(UBound(tempChildren)) = Array(1, childDict) ' 存储键值对 parentDict(1) = tempChildren ' 回写修改后的children数组 ' 将父节点添加到主results数组 ReDim Preserve results(UBound(results) + 1) results(UBound(results)) = Array(1, parentDict) ' 存储键值对 ' 示例访问方式: For Each item In results If item(0) = 1 Then ' 通过键值查找 parentNode = item(1) Response.Write "Parent Node Children Count: " & UBound(parentNode(1)) + 1 End If Next %>
代码说明:
数据结构设计:
使用Array(key, value)
格式存储键值对
多维数组存储复合结构(如parentDict包含多个属性)
核心操作:
' 添加元素操作模板 tempArray = originalArray ReDim Preserve tempArray(UBound(tempArray) + 1) tempArray(UBound(tempArray)) = NewElement originalArray = tempArray
优势与妥协:
✅ 纯数组实现,无需Scripting.Dictionary
❗ 查找需遍历数组(建议维护索引字典提升性能)
❗ 代码复杂度高于字典实现
封装类:
<% ' 带索引缓存的优化版本 Class ArrayDictionary Private dataArray Private indexMap Private Sub Class_Initialize() ReDim dataArray(-1) Set indexMap = Server.CreateObject("Scripting.Dictionary") End Sub Public Sub Add(key, value) If Not indexMap.Exists(key) Then ReDim Preserve dataArray(UBound(dataArray) + 1) dataArray(UBound(dataArray)) = value indexMap.Add key, UBound(dataArray) End If End Sub Public Property Get Item(key) If indexMap.Exists(key) Then Item = dataArray(indexMap(key)) End If End Property End Class ' 使用示例: Set results = New ArrayDictionary Set parentDict = New ArrayDictionary Set childDict = New ArrayDictionary parentDict.Add "children", New ArrayDictionary parentDict("children").Add 1, childDict results.Add 1, parentDict %>