Dictionary对象(字典对象)

来源:互联网 发布:linux uboot移植 编辑:程序博客网 时间:2024/04/28 00:34


许多Microsoft的编程语言,如Visual Basic、VBScript和Jscript,都提供集合(collection)。可以把集合想象为数组,可以使用其中内建的函数完成存储和操纵数据等基本任务。无须担心数据是在哪些行列,而是使用唯一的键进行访问。
VBScript和Jscript都提供类似的对象,通称Scripting.Dictionary对象或Dictionary对象。它类似于二维数组,把键和相关条目的数据存放在一起。然而真正的面向对象的方法,不应直接访问数据条目,必须使用Dictionary对象支持的方法和属性来实现。
本章提供了一些示例页面,允许试验脚本运行期对象的方法和属性。这些实例在下载的文件的文件的Chaper05子目录里。

创建和使用Dictionary对象

创建一个Dictionary对象的示例如下:
Dim objMyData
Set objMyData = Server.CreateObject(“Scripting.Dictionary”)


1.Dictionary对象的成员概要

当增加一个键/条目对时,如果该键已存在;或者删除一个键/条目对时,该关键字/条目对不存在,或改变已包含数据的Dictionary对象的CompareMode,都将产生错误。

2.Dictionary对象的属性和说明
CompareMode (仅用于VBScript)设定或返回键的字符串比较模式
Count 只读。返回Dictionary里的键/条目对的数量
Item(key) 设定或返回指定的键的条目值
Key(key) 设定键值

3.Dictionary对象的方法和说明
Add(key,item) 增加键/条目对到Dictionary
Exists(key) 如果指定的键存在,返回True,否则返回False
Items() 返回一个包含Dictionary对象中所有条目的数组
Keys() 返回一个包含Dictionary对象中所有键的数组
Remove(key) 删除一个指定的键/条目对
RemoveAll() 删除全部键/条目对

4.举例说明

<%
Dim Dic,KeyValue,ItemValue
KeyValue="Key_get123"
ItemValue="Value_hao123"
Set Dic = Server.CreateObject("Scripting.Dictionary")
Dic.Add KeyValue,ItemValue
Dic.Add "MyKey","MyValue"
Response.Write(Dic.Item("Key_get123") & "
")
Response.Write(Dic.Item("MyKey") & "
")


arrKeysArray = Dic.Keys          
arrItemsArray = Dic.Items        
For intLoop = 0 To Dic.Count - 1  
    Response.Write("Key: " & arrKeysArray(intLoop)&"_Value: "&arrItemsArray(intLoop)&"
")
Next

If Dic.Exists("MyKey") then
    Dic.Remove("MyKey")
End if

arrKeysArray = Dic.Keys          
arrItemsArray = Dic.Items        
For intLoop = 0 To Dic.Count - 1  
    Response.Write("Key: " & arrKeysArray(intLoop)&"_Value: "&arrItemsArray(intLoop)&"
")
Next

Dic.RemoveAll()

arrKeysArray = Dic.Keys          
arrItemsArray = Dic.Items        
For intLoop = 0 To Dic.Count - 1  
    Response.Write("Key: " & arrKeysArray(intLoop)&"_Value: "&arrItemsArray(intLoop)&"
")
Next


Set Dic=Nothing

%>

原创粉丝点击