萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP For Each Next 迴圈:集合迭代、陣列遍歷與 Dictionary 應用

VBScript For Each 迴圈深度解析:集合迭代的優雅之道

For Each Next 專為集合、陣列、Dictionary 等可列舉物件設計,語意清晰且不易出現索引越界錯誤。本文詳細說明適用物件類型、迭代變數特性、巢狀迭代與常見陷阱。

適用物件類型

物件類型迭代內容範例
陣列每個元素值Array(1,2,3)
Collection每個項目Request.Form, Request.QueryString
Dictionary每個 Key(需搭配 .Keys 或 .Items)Server.CreateObject("Scripting.Dictionary")
Recordset不直接支援(需用 Do While)-
FileSystemObject 資料夾/檔案集合每個 File/Folder 物件folder.Files, folder.SubFolders

基本語法與陣列迭代

<%
Dim fruits, fruit
fruits = Array("蘋果", "香蕉", "櫻桃", "蓮霧")

For Each fruit In fruits
    Response.Write fruit & "
" Next ' 輸出:蘋果 香蕉 櫻桃 蓮霧 %>

Dictionary 迭代完整範例

<%
Dim dict, key, val
Set dict = Server.CreateObject("Scripting.Dictionary")
dict.CompareMode = 1 ' vbTextCompare,不區分大小寫

dict.Add "username", "john_doe"
dict.Add "email", "john@example.com"
dict.Add "role", "admin"
dict.Add "last_login", Now()

' 方式一:迭代 Keys,再取值
Response.Write "

方式一:Keys 迭代

" For Each key In dict.Keys Response.Write key & " = " & dict(key) & "
" Next ' 方式二:迭代 Items(僅取值,無 Key) Response.Write "

方式二:Items 迭代

" For Each val In dict.Items Response.Write val & "
" Next ' 方式三:建立下拉選單(修正原始碼邏輯錯誤) Response.Write "

方式三:下拉選單

" Response.Write "" %>

修正原始碼中的下拉選單 Bug

<%
' ❌ 原始碼錯誤:使用未宣告的 i 變數當作 option value
' For Each item In some_array
'     response.write("")
'     i = i + 1
' Next

' ✅ 正確:直接用 item 或 key 當 value
Sub CreateSelect(name, dictObj)
    Response.Write ""
End Sub

' 使用範例
Dim bookTypes : Set bookTypes = Server.CreateObject("Scripting.Dictionary")
bookTypes.Add "classic", "經典文學"
bookTypes.Add "scifi", "科幻小說"
bookTypes.Add "mystery", "推理懸疑"
Call CreateSelect("book_type", bookTypes)
%>

Request 集合迭代:除錯神器

<%
' 顯示所有表單欄位與值
Response.Write "

Request.Form

" For Each key In Request.Form Response.Write key & " = " & Request.Form(key) & "
" Next ' 顯示所有 QueryString 參數 Response.Write "

Request.QueryString

" For Each key In Request.QueryString Response.Write key & " = " & Request.QueryString(key) & "
" Next ' 顯示所有 ServerVariables(環境變數) Response.Write "

ServerVariables

" For Each key In Request.ServerVariables Response.Write key & " = " & Request.ServerVariables(key) & "
" Next %>

FileSystemObject 目錄遞迴掃描

<%
Sub ListFolderContents(folderPath, depth)
    Dim fso, folder, file, subFolder
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(Server.MapPath(folderPath))
    
    Response.Write String(depth * 2, " ") & "📁 " & folder.Name & "
" For Each file In folder.Files Response.Write String(depth * 2 + 2, " ") & "📄 " & file.Name & " (" & FormatFileSize(file.Size) & ")
" Next For Each subFolder In folder.SubFolders Call ListFolderContents(folderPath & "/" & subFolder.Name, depth + 1) Next End Sub Function FormatFileSize(bytes) If bytes < 1024 Then FormatFileSize = bytes & " B" ElseIf bytes < 1024 * 1024 Then FormatFileSize = Round(bytes / 1024, 1) & " KB" Else FormatFileSize = Round(bytes / (1024 * 1024), 1) & " MB" End Function Call ListFolderContents("/uploads", 0) %>

關鍵限制與注意事項

  • 無法直接修改集合大小:迭代過程中 Add/Remove 會報錯
  • 迭代順序不保證:Dictionary/Collection 順序非插入序
  • 無索引存取:需配合計數器變數取得索引
  • 唯讀迭代變數:For Each item In arr : item = "new" : Next 不會修改陣列原值

效能比較:For Each vs For Index

<%
' 大陣列測試
Dim largeArr, i, start, elapsed
ReDim largeArr(100000)
For i = 0 To 100000 : largeArr(i) = "Item " & i : Next

' For Index
start = Timer()
For i = 0 To UBound(largeArr)
    Dim x : x = largeArr(i)
Next
elapsed = Timer() - start
Response.Write "For Index: " & elapsed & " 秒
" ' For Each start = Timer() For Each item In largeArr Dim y : y = item Next elapsed = Timer() - start Response.Write "For Each: " & elapsed & " 秒
" ' 通常 For Each 略快 10-20% %>
copyright © 萬盛學電腦網 all rights reserved