ASP.NET Razor - VB 循環(huán)和數(shù)組


語句在循環(huán)中會被重復(fù)執(zhí)行。


For 循環(huán)

如果您需要重復(fù)執(zhí)行相同的語句,您可以設(shè)定一個循環(huán)。

如果您知道要循環(huán)的次數(shù),您可以使用 for 循環(huán)。這種類型的循環(huán)在向上計數(shù)或向下計數(shù)時特別有用:

實例

<html>
<body>
@for i=10 to 21
   @<p>Line @i</p>
next i
</body>
</html>

運行實例 ?

點擊 "運行實例" 按鈕查看在線實例


For Each 循環(huán)

如果您使用的是集合或者數(shù)組,您會經(jīng)常用到 for each 循環(huán)

集合是一組相似的對象,for each 循環(huán)可以遍歷集合直到完成。

下面的實例中,遍歷 ASP.NET Request.ServerVariables 集合。

實例

<html>
<body>
<ul>
@for each x in Request.ServerVariables
    @<li>@x</li>
next x
</ul>
</body>
</html>

運行實例 ?

點擊 "運行實例" 按鈕查看在線實例


While 循環(huán)

while 循環(huán)是一個通用的循環(huán)。

while 循環(huán)以 while 關(guān)鍵字開始,后面緊跟著括號,您可以在括號里規(guī)定循環(huán)將持續(xù)多久,然后是重復(fù)執(zhí)行的代碼塊。

while 循環(huán)通常會設(shè)定一個遞增或者遞減的變量用來計數(shù)。

下面的實例中,+= 運算符在每執(zhí)行一次循環(huán)時給變量 i 的值加 1。

實例

<html>
<body>
@Code
Dim i=0
Do While i < 5
    i += 1
    @<p>Line @i</p>
Loop
End Code
</body>
</html>

運行實例 ?

點擊 "運行實例" 按鈕查看在線實例



數(shù)組

當您要存儲多個相似變量但又不想為每個變量都創(chuàng)建一個獨立的變量時,可以使用數(shù)組來存儲:

實例

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

運行實例 ?

點擊 "運行實例" 按鈕查看在線實例