日期:2009-06-14  浏览次数:20749 次


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

5.3.1 创建和使用Dictionary对象
    创建一个Dictionary对象的示例如下:
    ‘In VBScript:
    Dim objMyData
    Set objMyData = Server.CreateObject(“Scripting.Dictionary”)

    //In Jscript:
    var objMyData = Server.CreateObject(‘Scripting.Dictionary’);

    <!-- Server-Side with an OBJECT element -->
    <OBJECT RUNAT=”SERVER” SCOPE=”PAGE” ID=”objMyData”
            PROGID=”Scripting.Dictionary”>
    </OBJECT>
    Dictionary对象还可用于客户端的IE中。
1.    Dictionary对象的成员概要
表5-2和表5-3列出了Dictionary对象的属性和方法及相应的说明。
当增加一个键/条目对时,如果该键已存在;或者删除一个键/条目对时,该关键字/条目对不存在,或改变已包含数据的Dictionary对象的CompareMode,都将产生错误。
表5-2  Dictionary对象的属性和说明
属 性    说 明
CompareMode    (仅用于VBScript)设定或返回键的字符串比较模式
Count    只读。返回Dictionary里的键/条目对的数量
Item(key)    设定或返回指定的键的条目值
Key(key)    设定键值
表5-3  Dictionary对象的方法和说明
方 法    说 明
Add(key,item)    增加键/条目对到Dictionary
Exists(key)    如果指定的键存在,返回True,否则返回False
Items()    返回一个包含Dictionary对象中所有条目的数组
Keys()    返回一个包含Dictionary对象中所有键的数组
Remove(key)    删除一个指定的键/条目对
RemoveAll()    删除全部键/条目对
2.    对Dictionary中增加和删除条目
一旦得到一个新的(空的)Dictionary,可以对其添加条目,从中获取条目以及删除条目:
‘ In VBScript:
objMyData.Add “MyKey”, “MyItem”            ‘Add Value MyItem with key MyKey
objMyData.Add “YourKey”, ”YourItem”        ‘Add value YourItem with key YourKey
blnIsThere = objMyData.Exists(“MyKey”)        ‘Returns True because the item exists
strItem = objMyData.Item(“YourKey”)            ‘Retrieve value of YourKey
strItem = objMyData.Remove(“MyKey”)        ‘Retrieve and remove YourKey
objMyData.RemoveAll                        ‘Remove all the items
在JScript中,等价的代码为:
// In JScript;
objMyData.Add (‘MyKey’, ‘MyItem’);            //Add Value MyItem with key MyKey
objMyData.Add (‘YourKey’, ‘YourItem’);        //Add value YourItem with key YourKey
var blnIsThere = objMyData.Exists(‘MyKey’);    //Returns True because the item exists
var strItem = objMyData.Item(‘YourKey’);        //Retrieve value of YourKey
var strItem = objMyData.Remove(‘MyKey’);    //Retrieve and remove YourKey
objMyData.RemoveAll();                    //Remove all the items
3.    修改键或条目的值
可以通过修改键的值,或通过修改与特定的键关联的条目的数据,来改变存储在Dictionary内的数据。下面的代码改变键为MyKey的条目中的数据。
ObjMyData.Item(“MyKey”) = “NewValue”        ‘ In VBScript
ObjMyData.Item(‘MyKey’) = ‘NewValue’;        // In JScript
如果指定的键在Dictionary未找到,将在D