我基本上尝试使用带有子词典作为每个键的项目的字典在 vbscript 中创建多维关联数组。
有效:
myAssocArray =
"app1" =
"appid" => "1"
"name" => "alpha"
"app2" =
"appid" => "2"
"name" => "beta"
这是我的代码。它很好地循环遍历每个字典,但是当它到达子字典时,它总是回显“最后一个”元素的值。因此,当回显“app1”时,它将显示“2”的appid和“beta”的名称,但它应该分别显示“1”和“alpha”。
Dim dict
Dim dict2
Set dict = CreateObject("Scripting.Dictionary")
Set dict2 = CreateObject("Scripting.Dictionary")
' Create a dictionary to be used as the "items" value for the main dictionary
dict2.Add "appid", "1"
dict2.Add "name", "alpha"
' Add it to the main dictionary as the item with Key of "1"
dict.Add "app1", dict2
' Clear the temp second dictionary
dict2.RemoveAll
' Add a new dictionary dimension for the second item
dict2.Add "appid", "2"
dict2.Add "name", "beta"
dict.Add "app2", dict2
' Loop through the main dictionary, and go through each item (sub-dictionary)
For Each key In dict.Keys
MsgBox key
For Each key2 In dict.Item(key).Keys
MsgBox dict.Item(key).Item(key2)
Next
Next
打印出来
app1 =
"appid" = "2"
"name" = "beta"
app2 =
"appid" = "2"
"name" = "beta"
完全跳过第一项的值。知道为什么吗?
最佳答案
dict.Add“app1”,dict2
这将添加对 dict2
的引用,而不是副本,因此对 dict2
的任何后续更改都将反射(reflect)在 “app1”中
项目。
(在脚本末尾,"app1"
、"app2"
和 dict2
都是相同的字典)
您需要一个新的字典,而不是RemoveAll
,因此重复Set dict2 = CreateObject("Scripting.Dictionary")
关于dictionary - VBScript 中的多维字典总是获取最后一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219652/