VBS基礎篇 - vbscript Dictionary對象
Dictionary是存儲數據鍵和項目對的對象,其主要屬性有Count、Item、Key,主要方法有Add、Exists、Items、Keys、Remove、RemoveAll。
創(chuàng)建Dictionary對象
'定義并創(chuàng)建Dictionary對象,使用CreateObject創(chuàng)建并返回自動化對象的引用 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種常用的循環(huán)方法,具體代碼如下:
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 '循環(huán)遍歷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腳本和windows定時任務實現qq消息表情包定時發(fā)送功能
這篇文章主要介紹了vbs腳本和windows定時任務實現qq消息表情包定時發(fā)送,整個過程不用過多的程序運行,我們借助vbs腳本和windows定時任務去實現這一功能,需要的朋友可以參考下2022-01-01教你編寫Windows的VBScript與Mac的AppleSCript腳本解放雙手
這篇文章主要介紹了教你編寫Windows的VBScript腳本與Mac的AppleSCript腳本來解放大家的雙手,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-02-02用VBS調用程序并對程序的運行情況進行監(jiān)控的兩個代碼
用VBS調用程序并對程序的運行情況進行監(jiān)控的兩個代碼...2007-03-03使用 Iisext.vbs 列出 Web 服務擴展文件的方法
這篇文章主要介紹了如何使用 iisext.vbs 在本地或遠程計算機上列出 Web 服務擴展文件,需要的朋友可以參考下2014-07-07