ASP Dictionary

Scripting.Dictionary 的增删改查、存在判断、遍历与比较模式。

Intermediate
Key PointsDictionary 是 VBScript 里唯一的键值容器:查键用 Exists,取不到值会新建键而不是报错。

基本操作

ASP
<%
    Dim d
    Set d = Server.CreateObject("Scripting.Dictionary")

    d.Add "name", "Ada"
    d.Add "role", "admin"
    d("age") = 36                    ' 也可以直接赋值

    Response.Write d("name") & "<br>"
    Response.Write d.Count & " 项<br>"

    ' 改
    d("role") = "editor"

    ' 判断存在(必须!)
    If d.Exists("email") Then
        Response.Write d("email")
    Else
        Response.Write "没有 email"
    End If

    ' 删
    d.Remove "age"
    d.RemoveAll
%>
Output
Ada
3 项
没有 email

d("missing") does not error — it creates the key and returns Empty. Always If d.Exists(k) before reading, or the dictionary quietly fills with empty keys.

遍历

ASP
<%
    Dim k
    For Each k In d.Keys
        Response.Write k & " = " & d(k) & "<br>"
    Next

    ' 单独拿数组
    Dim keys, items
    keys = d.Keys
    items = d.Items
    Response.Write UBound(keys) + 1 & " 个键"
%>
Output
name = Ada
role = editor
2 个键

d.Keys and d.Items return arrays usable with UBound and Split. Do not Remove the current item while enumerating — it upsets the enumerator and skips entries or errors.

CompareMode

ASP
<%
    d.CompareMode = 1                ' 1 = Text(不区分大小写),0 = Binary(默认)

    d("Name") = "Ada"
    Response.Write d.Exists("name")  ' True(Text 模式)
%>
Output
True

The default Binary mode is case-sensitive, so d("Name") and d("name") are separate keys. CompareMode can only be set while the dictionary is empty; changing it later raises an error.

实用场景

ASP
<%
    ' 统计词频
    Dim words, w, freq
    words = Split("asp is easy asp is fast", " ")
    Set freq = Server.CreateObject("Scripting.Dictionary")

    For Each w In words
        If freq.Exists(w) Then
            freq(w) = freq(w) + 1
        Else
            freq(w) = 1
        End If
    Next

    Dim k
    For Each k In freq.Keys
        Response.Write k & ":" & freq(k) & "<br>"
    Next
%>
Output
asp:2
is:2
easy:1
fast:1

去重

ASP
<%
    Dim seen, out_, v
    Set seen = Server.CreateObject("Scripting.Dictionary")
    out_ = ""

    For Each v In Array("a", "b", "a", "c", "b")
        If Not seen.Exists(v) Then
            seen.Add v, True
            out_ = out_ & v & " "
        End If
    Next

    Response.Write Trim(out_)
%>
Output
a b c
Dictionary is not thread-safe and does not survive a request unless stored in Application or Session. When stored in Application, lock around reads and writes or concurrent access loses keys or crashes.

与数组的取舍

Dictionary
Lookuparr(i),快d(key),哈希,快
Lookup by value要循环遍历Exists 直接判
Order有序无序(插入顺序不保证)
Size固定或 ReDim自动增长

Friends & Partners