如何将字典添加到数组中

时间:2012-05-23 10:38:24

标签: vbscript

简单示例:

Dim d, a(0)
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
Set a(0) = d

WScript.Echo(TypeName(a))

输出:

Variant()

我没有看到任何方法如何访问这个对象,它计数3,但它似乎是空的

我发现谷歌没有列出这个问题的任何有用结果 - 如何在数组中分配字典,这令人惊讶?

最近我发现这是未答复的link

我的问题是我有一个创建临时字典的循环,我计划用简单的一维数组提供字典对象,但没有成功

我还发现了类似link的内容,其中两个数组分别为字典键和字典项(值)创建,这对我的案例来说太复杂了

这对VBScript来说是否可行?

2 个答案:

答案 0 :(得分:3)

我可能误解了你的问题,但你可以像这样访问字典:

WScript.Echo(a(0).Item("b"))

修改

此代码:

Dim d, a(0)
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
Set a(0) = d
WScript.Echo(a(0).Item("b"))

dim x
x = d.Items

dim i
for i = lbound(x) to ubound(x)
    WScript.Echo(x(i))
next

在我的Windows 7计算机上生成此输出:

C:\>cscript test.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

Belgrade
Athens
Belgrade
Cairo

C:\>

答案 1 :(得分:0)

一个例子:

Dim d
Set d = CreateObject("Scripting.Dictionary") 
d.Add "a", "Athens" 
d.Add "b", "Belgrade" 
d.Add "c", "Cairo" 

WScript.Echo(d("a")) '=> Athens

d("a") = "Brussels"

WScript.Echo(d("a")) '=> Brussels

a = d.Keys   ' Get the keys.
b = d.Items
For i = 0 To d.Count -1 ' Iterate the array.
  wscript.echo a(i) & " " & b(i)
Next


'=>a Brussels
'=>b Belgrade
'=>c Cairo