ASP Dictionary 對象
Dictionary 對象用於在名稱/值對中存儲資訊。

嘗試一下 - 實例
指定的鍵存在嗎?
本例演示如何創建一個 Dictionary 對象,然後使用 Exists 方法來檢查指定的鍵是否存在。
返回一個所有專案的數組
本例演示如何使用 Items 方法來返回一個所有專案的數組。
返回一個所有鍵的數組
本例演示如何使用 Keys 方法來返回一個所有鍵的數組。
返回一個專案的值
本例演示如何使用 Item 屬性來返回一個專案的值。
設置一個鍵
本例演示如何使用 Key 屬性來在 Dictionary 對象中設置一個鍵。
返回鍵/專案對的數量
本例演示如何使用 Count 屬性來返回鍵/專案對的數量。
Dictionary 對象
Dictionary 對象用於在名稱/值對(等同於鍵和專案)中存儲資訊。Dictionary 對象看似比數組更為簡單,然而,Dictionary 對象卻是更令人滿意的處理關聯數據的解決方案。
比較 Dictionaries 和數組:
- 鍵用於識別 Dictionary 對象中的專案
- 您無需調用 ReDim 來改變 Dictionary 對象的尺寸
- 當從 Dictionary 中刪除一個專案時,其餘的專案會自動上移
- Dictionary 不是多維,而數組是多維
- Dictionary 比數組帶有更多的內建函數
- Dictionary 在頻繁地訪問隨機元素時,比數組工作得更好
- Dictionary 在根據它們的內容定位專案時,比數組工作得更好
下麵的實例創建了一個 Dictionary 對象,並向對象添加了一些鍵/專案對,然後取回了鍵 gr 的專案值:
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>
輸出:
The value of key gr is: Green
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>
輸出:
The value of key gr is: Green
Dictionary 對象的屬性和方法描述如下:
屬性
屬性 | 描述 |
---|---|
CompareMode | 設置或返回用於在 Dictionary 對象中比較鍵的比較模式。 |
Count | 返回 Dictionary 對象中鍵/專案對的數目。 |
Item | 設置或返回 Dictionary 對象中一個專案的值。 |
Key | 為 Dictionary 對象中已有的鍵值設置新的鍵值。 |
方法
方法 | 描述 |
---|---|
Add | 向 Dictionary 對象添加新的鍵/專案對。 |
Exists | 返回一個布爾值,這個值指示指定的鍵是否存在於 Dictionary 對象中。 |
Items | 返回 Dictionary 對象中所有專案的一個數組。 |
Keys | 返回 Dictionary 對象中所有鍵的一個數組。 |
Remove | 從 Dictionary 對象中刪除指定的鍵/專案對。 |
RemoveAll | 刪除 Dictionary 對象中所有的鍵/專案對。 |