VBS基础篇 - 对象(2) - Dictionary对象

Dictionary是存储数据键和项目对的对象,其主要属性有CountItemKey,主要方法有AddExistsItemsKeysRemoveRemoveAll

  创建Dictionary对象  

'定义并创建Dictionary对象,使用CreateObject创建并返回自动化对象的引用
Dim Dic
Set Dic = CreateObject("Scripting.Dictionary")

   添加键值  

Dim Dic
Set Dic = CreateObject("Scripting.Dictionary")
'向Dictionary对象中添加键值对
Dic.Add "Name", "Sirrah"    'Add方法第一个参数是Key值,第二个是Item值
Dic.Add "Age", 23  

   删除键值        

Dim Dic
Set Dic = CreateObject("Scripting.Dictionary")
Dic.Add "Name", "Sirrah"   '向Dictionary对象中添加键值对
Dic.Add "Age", 23
Dic.Remove("Age") '删除键Age的值
MsgBox Dic.Item("Age") '直接输出空白

  修改键值        

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 

  判断键是否存在  

Dim Dic
Set Dic = CreateObject("Scripting.Dictionary")
Dic.Add "Name", "Sirrah"   '向Dictionary对象中添加键值对
Dic.Add "Age", 23
MsgBox Dic.Exists("Age") '判断键是否存在  

   输出所有键值

输出Dictionary对象所有键值,这边将介绍2种常用的循环方法,具体代码如下:

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

 

posted @ 2012-01-12 22:23  Sirrah  阅读(2443)  评论(0编辑  收藏  举报