VBScript Do..While 語句



當我們想要在條件為真的情況下重複一組語句時,會使用 Do..While 迴圈。可以在迴圈的開頭或結尾檢查條件。

語法

VBScript 中 Do..While 迴圈的語法為 -

Do While condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop           

流程圖

VBScript Do..While statement

示例

以下示例使用 Do..while 迴圈在迴圈開頭檢查條件。僅當條件變為 True 時,才會執行迴圈內的語句。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">        
         Do While i < 5
            i = i + 1
            Document.write("The value of i is : " & i)
            Document.write("<br></br>")
         Loop         
      </script>
   </body>
</html>

執行上述程式碼後,將在控制檯中列印以下輸出。

The value of i is : 1

The value of i is : 2

The value of i is : 3

The value of i is : 4

The value of i is : 5

備用語法

另外還有一種備用 Do..while 迴圈的語法,用於在迴圈結束時檢查條件。這兩個語法之間最主要的差異透過示例解釋如下。

Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop While condition

流程圖

VBScript Do..While statement

示例

以下示例使用 Do..while 迴圈在迴圈結束時檢查條件。即使條件為 False,也將至少執行一次迴圈內的語句。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">        
         i = 10  
         Do      
            i = i + 1
            Document.write("The value of i is : " & i)
            Document.write("<br></br>")
         Loop While i<3 'Condition is false.Hence loop is executed once.
         
      </script>
   </body>
</html>

執行上述程式碼後,將在控制檯中列印以下輸出。

The value of i is : 11
vbscript_loops.htm
廣告
© . All rights reserved.