VBS基础篇 - VBScript Dictionary对象
VBScript Dictionary对象是存储数据键和项目对的对象,主要属性有Count、Item、Key,主要方法有Add、Exists、Items、Keys、Remove、RemoveAll。
Dictionary对象的创建
可以使用CreateObject创建Dictionary对象,代码如下:
```vb
Dim Dic
Set Dic = CreateObject("Scripting.Dictionary")
```
添加键值对
可以使用Add方法向Dictionary对象中添加键值对,代码如下:
```vb
Dic.Add "Name", "Sirrah"
Dic.Add "Age", 23
```
删除键值
可以使用Remove方法删除Dictionary对象中的键值对,代码如下:
```vb
Dic.Remove "Age"
```
判断键是否存在
可以使用Exists方法判断键是否存在,代码如下:
```vb
If Dic.Exists("Age") Then
MsgBox "Age键存在!"
Else
MsgBox "Age键不存在!"
End If
```
遍历Dictionary对象
可以使用For Each循环遍历Dictionary对象的键,代码如下:
```vb
For Each Dic In Dics
MsgBox Dics.Item(Dic)
Next
```
也可以使用For循环遍历Dictionary对象的键,代码如下:
```vb
For i = 0 To dic.Count - 1
str = str & Dics(i) & vbCrlf
Next
```
统计键值对个数
可以使用Count属性统计Dictionary对象中的键值对个数,代码如下:
```vb
WScript.Echo "字典中现有键值对数量: " & Dict.Count
```
实例脚本文件
以下是一个实例脚本文件,包含字典的添加、删除、判断键是否存在、修改键、修改值、遍历、统计键值对个数等操作:
```vb
'建立字典
Dim Dict : Set Dict = CreateObject("Scripting.Dictionary")
'添加键值对
Dict.Add "Key1", "Item1"
Dict.Add "Key2", "Item2"
Dict.Add "Key3", "Item3"
'字典中键值对数量
WScript.Echo "字典中现有键值对数量: " & Dict.Count
'检查指定键是否存在
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
'遍历字典
Sub TraverseDict
Dim DictKeys, DictItems, Counter
DictKeys = Dict.Keys
DictItems = Dict.Items
For Counter = 0 To Dict.Count - 1
WScript.Echo "键: " & DictKeys(Counter) & ",值: " & DictItems(Counter)
Next
End Sub
```
Dictionary对象是VBScript中一种非常有用的数据结构,可以用来存储和管理大量的键值对数据。