ASP.NET Razor - VB 循環和數組

語句可以在循環中重復執行。

For 循環

如果需要重復運行相同的語句,您可以編寫一個循環。

如果您能夠確定循環的次數,則可以使用 for 循環。這種循環類型是專門為計數或反向計數設計的:

實例

<html>
<body>
@For i=10 To 21
    @<p>Line #@i</p>
Next i
</body>
</html>

運行實例

For Each 循環

如果您需要處理集合或數組,則通常要用到 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>

運行實例

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>

運行實例

數組

如果您需要存儲相似的變量,但又不希望為每個項目創建獨立的變量,那么數組就派上用場了:

實例

@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>

運行實例