'For each item in the collection, display its value. For Each Item in Session.Contents Response.Write Session.Contents(Item) & "<BR>" Next %> 可以使用 VBScript 中的 For...Next 语句遍历集合。例如,要列出上例中存储在 Session 中的三个项目,可以使用下列语句。
<% 'Declare a counter variable. Dim Item
'Repeat the loop until the value of counter is equal to 3. For Item = 1 to 3 Response.Write Session.Contents(Item) & "<BR>" Next %> 因为一般不知道存储在集合中的项目个数,ASP 支持集合的 Count 属性,这个属性返回集合中的项目数。可以使用 Count 属性指定计数器的终值。
<% 'Declare a counter variable. Dim Item
'Repeat this loop until the counter equals the number of items 'in the collection. For Item = 1 to Session.Contents.Count Response.Write Session.Contents(Item) & "<BR>" Next %> 可以在脚本中使用 for 语句在集合中循环。在 JScript 的 for 语句中使用 Count 属性时,为了收到更大的效果,应该将 Count 值分配给本地变量并使用该变量设置计数器终值。这样,脚本引擎就不需要每次循环都查寻 Count 的值。下面的例子展示了这个技巧:
<% var item, numitems; numitems = Session.Contents.Count; for (item = 1; item <= numitems; item++) { Response.Write(Session.Contents(item) + "<BR>") } %> Microsoft JScript 3.0 引入了 Enumerator 对象。可以使用该对象遍历 ASP 集合。atEnd 方法指出了集合中是否还存在项目。moveNext 方法移动到集合中的下一个项目。
<% // Create an Enumerator object var mycoll = new Enumerator(Session.Contents);
//Iterate through the collection and display each item while (!mycoll.atEnd()) { var x = mycoll.item(); Response.Write(Session.Contents(x) + "<BR>"); mycoll.moveNext(); } %> 遍历带子关键字 (Subkeys) 的集合 脚本在单一 cookie 中嵌入相关值以减少在浏览器和 Web 服务器之间传送的 cookie 数目。因此 Request 和 Response 对象的 Cookies 集合能够在单一项目中拥有多个值。这些子项目或子关键字可以被单个访问。只有 Request.Cookies 和 Response.Cookies 集合支持子关键字 (Subkeys)。Request.Cookies 只支持读操作;Response.Cookies 只支持写操作。
'Display the entire cookie collection. For Each Cookie in Request.Cookies Response.Write Cookie & "<BR>" If Request.Cookies(Cookie).HasKeys Then 'Display the subkeys For Each Subkey in Request.Cookies(Cookie) Response.Write Subkey & "=" & Request.Cookies(Cookie)(Subkey) & "<BR>" Next Else Response.Write "No subkeys in this cookie <BR>" End If Next %> 遍历对象集合 Session 和 Application 集合可以保存数量变量或者对象实例。Contents 集合拥有数量变量和通过调用 Server.CreateObject 生成的对象实例。StaticObjects 集合拥有在 Global.asa 文件中使用 HTML <OBJECT> 元素创建的对象。
<% For Each Object in Session.StaticObjects Session.StaticObjects(Object).InitializeUser Next %> ASP 集合有何不同之处? 尽管在本主题中讨论的 ASP 集合与 Visual Basic 的 Collection 对象非常相似,但还是有些不同。ASP 集合支持 Count 属性和 Item 方法,但不支持 Add 和 Remove 方法。