萬盛學電腦網

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

ASP (VBScript) 實現 Continue 跳過本次迴圈的三種寫法

問題

VBScript 無 Continue 關鍵字。需以結構化方式達成「跳過本次迴圈剩餘邏輯,直接進入下一次迭代」。

寫法一:反向條件包裹 (最推薦、可讀性最佳)

Dim i
i = 0
Do While i < 5
  i = i + 1
  If i <> 3 Then ' 只處理非 3 的情況
    ' MsgBox "I'm not 3, I'm " & i
    ' Do something else...
  End If
Loop

寫法二:單次迴圈包裹 (模擬 Continue)

Dim i, j
i = 0
Do While i < 5
  i = i + 1
  For j = 1 To 1 ' 單次迴圈即可用 Exit For 跳出
    If i = 3 Then Exit For
    ' MsgBox "I'm not 3, I'm " & i
    ' Do something else...
  Next
Loop

寫法三:Goto 標籤 (不推薦、僅供舊代碼維護參考)

Dim i
i = 0
Do While i < 5
  i = i + 1
  If i = 3 Then GoTo ContinueLoop
  ' MsgBox "I'm not 3, I'm " & i
  ' Do something else...
ContinueLoop:
Loop

效能與風格比較

寫法優點缺點建議
反向條件包裹結構清晰、無額外變數、效能最好巢狀層級增加一層✅ 首選
單次 For 迴圈語意接近 Continue、可在多處 Exit For多一個迴圈變數、微小效能損耗次選
GoTo可跳至任意位置破壞結構化、難維護、易產生義大利麵條代碼❌ 禁用

For Each 陣列遍歷的 Continue 模式

Dim arr, item, skipFlag
arr = Array(1,2,3,4,5)
For Each item In arr
  skipFlag = False
  If item = 3 Then skipFlag = True
  If Not skipFlag Then
    Response.Write item & "
" End If Next

現代化建議

若專案允許使用 JScript (同頁面 <script language="JScript" runat="server">),JScript 原生支援 continue、break、try/catch,複雜流程控制可寫在 JScript 函式中供 VBScript 呼叫。

copyright © 萬盛學電腦網 all rights reserved