ASP.NET Razor - VB 迴圈和數組
語句在迴圈中會被重複執行。
For 迴圈
如果您需要重複執行相同的語句,您可以設定一個迴圈。
如果您知道要迴圈的次數,您可以使用 for 迴圈。這種類型的迴圈在向上計數或向下計數時特別有用:
實例
<html>
<body>
@For i=10 To 21
@<p>Line #@i</p>
Next i
</body>
</html>
<body>
@For i=10 To 21
@<p>Line #@i</p>
Next i
</body>
</html>
For Each 迴圈
如果您使用的是集合或者數組,您會經常用到 for each 迴圈。
集合是一組相似的對象,for each 迴圈可以遍曆集合直到完成。
下麵的實例中,遍曆 ASP.NET Request.ServerVariables 集合。
實例
<html>
<body>
<ul>
@For Each x In Request.ServerVariables
@<li>@x</li>
Next x
</ul>
</body>
</html>
<body>
<ul>
@For Each x In Request.ServerVariables
@<li>@x</li>
Next x
</ul>
</body>
</html>
While 迴圈
while 迴圈是一個通用的迴圈。
while 迴圈以 while 關鍵字開始,後面緊跟著括弧,您可以在括弧裏規定迴圈將持續多久,然後是重複執行的代碼塊。
while 迴圈通常會設定一個遞增或者遞減的變數用來計數。
下麵的實例中,+= 運算符在每執行一次迴圈時給變數 i 的值加 1。
實例
<html>
<body>
@Code
Dim i=0
Do While i<5
i += 1
@<p>Line #@i</p>
Loop
End Code
</body>
</html>
<body>
@Code
Dim i=0
Do While i<5
i += 1
@<p>Line #@i</p>
Loop
End Code
</body>
</html>
數組
當您要存儲多個相似變數但又不想為每個變數都創建一個獨立的變數時,可以使用數組來存儲:
實例
@Code
Dim members As String()={"Jani","Hege","Kai","Jim"}
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=members(2-1)
end Code
<html>
<body>
<h3>Members</h3>
@For Each person In members
@<p>@person</p>
Next person
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>
Dim members As String()={"Jani","Hege","Kai","Jim"}
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=members(2-1)
end Code
<html>
<body>
<h3>Members</h3>
@For Each person In members
@<p>@person</p>
Next person
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>