字典 (dictionary) 是一種非線性的資料結構,其內部儲存多對鍵 (key)、值 (value) 組合,鍵做為存取值的索引存取值。由於字典內部的演算法,字典並不是直接儲存鍵和值,而是將鍵經雜湊函數 (hash function) 轉換成內部的索引後再取值,所以我們只能由鍵取值,不能由值取鍵。
在 VBScript 中,字典透過內建物件來支援,但字典是常用的資料結構,故我們提前說明。我們會在後文介紹物件的寫法,讀者可將後文和本文交互參考。
以下範例建立物件並存取值:
Set dict = CreateObject("Scripting.Dictionary")
' Add (key, value) pairs.
dict.Add "one", "eins"
dict.Add "two", "twei"
dict.Add "three", "drei"
' Retrieve value by key.
Assert dict.Item("one") = "eins", "Wrong value"
Assert dict.Item("two") = "zwei", "Wrong value"
Assert dict.Item("three") = "drei", "Wrong value"
' Home-made assert for VBScript
Sub Assert( boolExpr, strOnFail )
If Not boolExpr Then
Err.Raise vbObjectError + 99999, , strOnFail
End If
End Sub
以下範例利用鍵走訪字典:
Set dict = CreateObject("Scripting.Dictionary")
' Add (key, value) pairs.
dict.Add "one", "eins"
dict.Add "two", "twei"
dict.Add "three", "drei"
' Iterate over dict with its keys.
For Each k in dict.Keys
WScript.Echo k & " -> " & dict.Item(k)
Next
也可以直接以值來走訪字典:
Set dict = CreateObject("Scripting.Dictionary")
' Add (key, value) pairs.
dict.Add "one", "eins"
dict.Add "two", "twei"
dict.Add "three", "drei"
' Iterate over dict.
For Each item in dict.Items
WScript.Echo item
Next
但要注意這時無法反推鍵,這是受到字典內部實作的限制。
以下短例移除字典中的鍵/值對:
Set dict = CreateObject("Scripting.Dictionary")
' Add (key, value) pairs.
dict.Add "one", "eins"
dict.Add "two", "twei"
dict.Add "three", "drei"
' Check the existences of (k, v) pairs.
Assert dict.Exists("one") = True, "It should exit"
Assert dict.Exists("two") = True, "It should exist"
' Remove a (k, v) pair.
dict.Remove "two"
' Check the existences of (k, v) pairs.
Assert dict.Exists("one") = True, "It should exit"
Assert dict.Exists("two") = False, "It should not exist"
' Home-made assert for VBScript
Sub Assert( boolExpr, strOnFail )
If Not boolExpr Then
Err.Raise vbObjectError + 99999, , strOnFail
End If
End Sub
移除的方式是根據鍵為索引,一次移除掉整個鍵/值對。