1. Dictionary對象的成員概要
當增加一個(gè)鍵/條目對時(shí),如果該鍵已存在;或者刪除一個(gè)鍵/條目對時(shí),該關(guān)鍵字/條目對不存在,或改變已包含數據的Dictionary對象的CompareMode,都將產(chǎn)生錯誤。
屬 性 說(shuō) 明
CompareMode (僅用于VBScript)設定或返回鍵的字符串比較模式
Count 只讀。返回Dictionary里的鍵/條目對的數量 ---從1開(kāi)始,而不像數組從0開(kāi)始計數
Item(key) 設定或返回指定的鍵的值
Key(key) 設定鍵名值
方法說(shuō)明
Add(key,item) 增加鍵/條目對到Dictionary
Exists(key) 如果指定的鍵存在,返回True,否則返回False
Items() 返回一個(gè)包含Dictionary對象中所有條目的數組
Keys() 返回一個(gè)包含Dictionary對象中所有鍵的數組
Remove(key) 刪除一個(gè)指定的鍵/條目對
RemoveAll() 刪除全部鍵/條目對
2. 對Dictionary中增加和刪除條目
一旦得到一個(gè)新的(空的)Dictionary,可以對其添加條目,從中獲取條目以及刪除條目:
‘ In VBScript:
objMyData.Add “MyKey”, “MyItem”
objMyData.Add “YourKey”, ”YourItem”
blnIsThere = objMyData.Exists(“MyKey”)
strItem = objMyData.Item(“YourKey”)
strItem = objMyData.Remove(“MyKey”)
objMyData.RemoveAll
3. 修改鍵或條目的值
可以通過(guò)修改鍵的值,或通過(guò)修改與特定的鍵關(guān)聯(lián)的條目的數據,來(lái)改變存儲在Dictionary內的數據。下面的代碼改變鍵為MyKey的條目中的數據。
ObjMyData.Item(“MyKey”) = “NewValue” ‘ In VBScript
ObjMyData.Item(‘MyKey’) = ‘NewValue’; // In JScript
如果指定的鍵在Dictionary未找到,將在Dictionary中后面位置創(chuàng )建一個(gè)以MyKey為鍵,以New Value為其條目值的新的鍵/條目對。有意思的是,如果使用一個(gè)不存在的鍵來(lái)檢索條目,不僅得到一個(gè)空的字符串(這是可以想到的),而且還在Dictionary里添加一個(gè)新的鍵/條目對,鍵即是指定的鍵,但條目的數據為空。
可以使用Key屬性?xún)H改變鍵名的值而不改變與之對應的條目的數據。將一個(gè)已存在的鍵MyKey改變?yōu)镸yNewKey,可以用:
objMyData.Key(“MyKey”) = “MyNewValue” ‘ In VBScript
objMyData.Item(‘MyKey’) = ‘MyNewValue’; // In JScript
如果指定的鍵未找到,則產(chǎn)生運行期錯誤。
4. 設置比較模式
Dictionary的CompareMode屬性?xún)H適用于VBScript,不能在JScript中使用。當比較字符串鍵時(shí),允許指定比較的方式。兩個(gè)允許的值為BinaryCompare(0)和TextCompare(1)。BinaryCompare(0)為二進(jìn)制數對照(即區分大小寫(xiě));TextCompare(1)為文本對照(即不區分大小寫(xiě))。
5. 遍歷Dictionary
研究Dictionary時(shí),有兩個(gè)方法和一個(gè)屬性需要特別注意,它們允許我們遍歷存儲在Dictionary里的所有鍵/條目對。Items方法用一個(gè)一維數組的形式返回Dictionary里所有的條目數據,而keys方法用一個(gè)一維數組返回所有已存在的鍵值??梢允褂肅ount屬性得到鍵或條目的數量。
例如,可以使用下列代碼得到名稱(chēng)為objMyData的Dictionary中所有的鍵和條目值。注意,雖然Count屬性保存了在Dictionary里的鍵/條目數量,但VBScript和JScript的數組總是從下標0開(kāi)始的。因此,數組下標應從0到Count-1。
‘In VBScript:
arrKeys = objMyData.Keys ‘Get all the keys into an array
arrItems = objMyData.Items ‘Get all the items into an array
For intLoop = 0 To objMyData.Count –1 ‘Iterate through the array
StrThisKey = arrKeys(intLoop) ‘This is the key value
StrThisItem = arrItems(intLoop) ‘This is the item (data) value
Next
// In JScript
// Get VB-style arrays using the Keys() and Items() methods
var arrKeys = new VBArray(objMyData.Keys()).toArray();
var arrItems = new VBArray(objMyData.Items()).toArray();
for (intLoop = 0; intLoop < objMyData.Count; intLoop++) {
// Iterate through the arrays
strThisKey = arrKeys[intLoop]; // This is the key value
strThisItem = arrItems[intLoop]; // This is the item (data) value
}
在VBScript里也可以使用For Each … Next語(yǔ)句完成同樣的功能:
arrKeys = objMyData.Keys
arrItems = objMyData.Items
For Each objItem in arrItems
Response.Write objItem & “ = “ & arrItems(objItem) & “<BR>”
Next
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。