VBScript中的多维词典总是得到最后一个值吗? [英] Multi-dimensional Dictionary in VBScript always gets last values?

查看:55
本文介绍了VBScript中的多维词典总是得到最后一个值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是试图在vbscript中创建一个多维关联数组,使用带有子词典的字典作为每个键的项.

I'm basically trying to create a multi-dimensional associative array in vbscript using a dictionary with sub-dictionaries as the items for each key.

有效地:

myAssocArray = 
    "app1" =
        "appid" => "1"
        "name"  => "alpha"
    "app2" =
        "appid" => "2"
        "name"  => "beta"

这是我的代码.它可以很好地循环遍历每个字典,但是当到达子字典时,它总是回显出"last"元素的值.因此,在回显"app1"时,它将显示appid为"2"和名称为"beta",但应分别显示为"1"和"alpha".

This is my code. It loops through each dictionary fine, but when it gets to the subdictionary, it ALWAYS echos out the values of the "last" element. So when echoing "app1" it will show appid of "2" and name of "beta" but it should show "1" and "alpha" respectively.

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"

完全跳过第一项的值.知道为什么吗?

Completely skipping over the first item's values. Any idea why?

推荐答案

dict.Add "app1", dict2

这会将引用添加到dict2,而不是副本,因此对dict2的任何后续更改都将反映在"app1"项中.

This adds a reference to dict2 not a copy so any subsequent changes to dict2 will be reflected in the "app1" item.

(在脚本"app1""app2"dict2的末尾都是相同的字典)

(At the end of your script "app1", "app2" and dict2 are all the same Dictionary)

而不是RemoveAll,您需要一个新的Dictionary,因此重复Set dict2 = CreateObject("Scripting.Dictionary")

Rather than RemoveAll you need a new Dictionary so repeat Set dict2 = CreateObject("Scripting.Dictionary")

这篇关于VBScript中的多维词典总是得到最后一个值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆