欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

VBS基础篇 - vbscript Dictionary对象

程序员文章站 2022-06-17 22:10:56
dictionary是存储数据键和项目对的对象,其主要属性有count、item、key,主要方法有add、exists、items、keys、remove、removea...

dictionary是存储数据键和项目对的对象,其主要属性有count、item、key,主要方法有add、exists、items、keys、remove、removeall。
创建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.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

补充一个实例

脚本文件:a.vbs,包含字典的添加、删除、判断键是否存在、修改键、修改值、遍历、统计键值对个数

'建立字典
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

运行结果截图:

VBS基础篇 - vbscript Dictionary对象

相关标签: VBS Dictionary