萬盛學電腦網

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

ASP For Next 迴圈完整教學:語法、進階技巧與效能優化

VBScript For Next 迴圈完全指南:從基礎到進階模式

For Next 是 VBScript 中最基礎的計數迴圈結構。本文涵蓋語法細節、巢狀迴圈、Step 進階用法、效能陷阱與現代替代寫法。

基本語法結構

For counter = start To end [Step step]
    ' 迴圈主體
Next
  • counter:數值型變數,作為計數器
  • start:初始值
  • end:終止值(包含)
  • step:選填,遞增/遞減值,預設 1,可為負數

基礎範例

<%
' 基本遞增
For i = 1 To 5
    Response.Write i & "
" Next ' 輸出:1 2 3 4 5 ' Step 遞增 For i = 0 To 10 Step 2 Response.Write i & "
" Next ' 輸出:0 2 4 6 8 10 ' Step 遞減 For i = 10 To 1 Step -1 Response.Write i & "
" Next ' 輸出:10 9 8 7 6 5 4 3 2 1 %>

巢狀迴圈:九九乘法表經典實作

<%
Response.Write ""
For i = 1 To 9
    Response.Write ""
    Response.Write ""
    For j = 1 To 9
        Response.Write ""
    Next
    Response.Write ""
Next
Response.Write "
" & i & "" & (i * j) & "
" %>

進階技巧與陷阱

1. 迴圈變數作用域

<%
For i = 1 To 3
    ' 內層迴圈若也用 i,會覆蓋外層!
    For i = 1 To 2  ' ❌ 錯誤:覆蓋外層計數器
        Response.Write "Inner "
    Next
    ' 外層 i 已被改變,導致邏輯錯誤
Next
' ✅ 正確:使用不同變數名
For i = 1 To 3
    For j = 1 To 2
        Response.Write "Inner "
    Next
Next
%>

2. Step 為 0 會導致無限迴圈

<%
' ❌ 致命錯誤:無限迴圈
For i = 1 To 10 Step 0
    Response.Write i
Next
%>

3. 非整數 Step 的浮點數精度問題

<%
' ⚠️ 可能執行次數不如預期
For i = 0 To 1 Step 0.1
    Response.Write Round(i, 1) & "
" ' 可能輸出 0, 0.1, 0.2, ..., 0.9, 1 (11次) ' 或因浮點誤差少跑/多跑一次 Next ' ✅ 建議:用整數計數器,內部換算 For i = 0 To 10 Dim val : val = i / 10 Response.Write val & "
" Next %>

4. 提前結束:Exit For

<%
For i = 1 To 100
    If SomeCondition(i) Then
        Response.Write "找到於:" & i
        Exit For  ' 立即跳出迴圈
    End If
Next
%>

效能優化建議

  • 避免在迴圈內建立物件:將 CreateObject 移至迴圈外
  • 減少屬性存取:將常用屬性存入區域變數
  • 字串串接用陣列 + Join:不要在迴圈中 str = str & ...
  • 資料庫操作批次化:不要在迴圈中逐筆 Execute

現代替代:For Each 迭代集合

<%
' 適用於陣列、集合、Dictionary
Dim arr, item
arr = Array("Apple", "Banana", "Cherry")
For Each item In arr
    Response.Write item & "
" Next ' Dictionary 迭代 Dim dict : Set dict = Server.CreateObject("Scripting.Dictionary") dict.Add "key1", "Value 1" dict.Add "key2", "Value 2" For Each key In dict.Keys Response.Write key & " = " & dict(key) & "
" Next %>

遞迴 vs 迴圈:階乘計算比較

<%
' 迴圈版(推薦:無堆疊溢位風險)
Function FactorialLoop(n)
    Dim result, i
    result = 1
    For i = 2 To n
        result = result * i
    Next
    FactorialLoop = result
End Function

' 遞迴版(教學用,大數會堆疊溢位)
Function FactorialRec(n)
    If n <= 1 Then FactorialRec = 1 Else FactorialRec = n * FactorialRec(n - 1)
End Function
%>
copyright © 萬盛學電腦網 all rights reserved