Dictionary是存储数据键和项目对的对象,其主要属性有Count、Item、Key,主要方法有Add、Exists、Items、Keys、Remove、RemoveAll。
创建Dictionary对象
1
2
3
|
'定义并创建Dictionary对象,使用CreateObject创建并返回自动化对象的引用
Dim Dic
Set Dic = CreateObject( "Scripting.Dictionary" )
|
添加键值
1
2
3
4
5
|
Dim Dic
Set Dic = CreateObject( "Scripting.Dictionary" )
'向Dictionary对象中添加键值对
Dic.Add "Name" , "Sirrah" 'Add方法第一个参数是Key值,第二个是Item值
Dic.Add "Age" , 23
|
删除键值
1
2
3
4
5
6
|
Dim Dic
Set Dic = CreateObject( "Scripting.Dictionary" )
Dic.Add "Name" , "Sirrah" '向Dictionary对象中添加键值对
Dic.Add "Age" , 23
Dic.Item( "Age" ) = 22 '修改键Age的值
MsgBox Dic.Item( "Age" ) '输出22
|
判断键是否存在
1
2
3
4
5
|
Dim Dic
Set Dic = CreateObject( "Scripting.Dictionary" )
Dic.Add "Name" , "Sirrah" '向Dictionary对象中添加键值对
Dic.Add "Age" , 23
MsgBox Dic.Exists( "Age" ) '判断键是否存在
|
输出所有键值
输出Dictionary对象所有键值,这边将介绍2种常用的循环方法,具体代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Dim Dic,Dics
Set Dic = CreateObject( "Scripting.Dictionary" )
Dic.Add "Name" , "Sirrah" '向Dictionary对象中添加键值对
Dic.Add "Age" , 23
Dics = dic.Items 'Items返回一个包含所有Item值的数组
For i = 0 To dic.Count - 1 'Count返回Dictionary对象键数目
str = str & Dics(i) & vbCrlf
Next
MsgBox(str)
Dim Dic,Dics
Set Dics = CreateObject( "Scripting.Dictionary" )
Dics.Add "Name" , "Sirrah" '向Dictionary对象中添加键值对
Dics.Add "Age" , 23
For Each Dic In Dics '循环遍历Dictionary键,并输出键值
MsgBox Dics.Item(Dic)
Next
|
补充一个实例
脚本文件:a.vbs,包含字典的添加、删除、判断键是否存在、修改键、修改值、遍历、统计键值对个数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
'建立字典
Dim Dict : Set Dict = CreateObject( "Scripting.Dictionary" )
'添加键值对
Dict.Add "Key1" , "Item1"
Dict.Add "Key2" , "Item2"
Dict.Add "Key3" , "Item3"
'字典中键值对数量
WScript.Echo "字典中现有键值对数量: " & Dict.Count '让一个脚本在屏幕上显示文本信息
WScript.Echo
'检查指定键是否存在
If Dict.Exists( "Key1" ) Then
WScript.Echo "Key1 存在!"
Else
WScript.Echo "Key1 不存在!"
End If
If Dict.Exists( "Keyn" ) Then
WScript.Echo "Keyn 存在!"
Else
WScript.Echo "Keyn 不存在!"
End If
WScript.Echo
'遍历字典
Sub TraverseDict
Dim DictKeys, DictItems, Counter
DictKeys = Dict.Keys
DictItems = Dict.Items 'Items返回一个包含所有Item值的数组
For Counter = 0 To Dict.Count - 1 'Count返回Dictionary对象键数目
WScript.Echo _
"键: " & DictKeys(Counter) & _ '& 字符串连接运算符
"值: " & DictItems(Counter)
Next
End Sub
TraverseDict
WScript.Echo
'在一个键值对中,修改键或修改值
Dict.Key( "Key2" ) = "Keyx"
Dict.Item( "Key1" ) = "Itemx"
TraverseDict
WScript.Echo
'删除指定键
Dict.Remove( "Key3" )
TraverseDict
WScript.Echo
'删除全部键
Dict.RemoveAll
WScript.Echo "字典中现有键值对数量: " & Dict.Count
|
调用方法:通过双击a.bat调用,a.bat代码如下:
cscript a.vbs
pause
运行结果截图:
原文链接:http://www.cnblogs.com/wakey/p/5764737.html