语句可以在循环中重复执行。
For 循环
如果需要重复运行相同的语句,您可以编写一个循环。
如果您能够确定循环的次数,则可以使用 for 循环。这种循环类型是专门为计数或反向计数设计的:
实例
<html>
<body> http://www.baolig.com/
@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> http://www.shi-feng.com/
<body>
@Code
Dim i=0
Do While i<5
i += 1
@<p>Line #@i</p>
Loop http://shop.sdlnfy.com/
End Code
</body>
</html>
运行实例
数组
如果您需要存储相似的变量,但又不希望为每个项目创建独立的变量,那么数组就派上用场了:
实例
@Code http://www.79igo.com/
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>
运行实例 http://www.xiaoyeping.com/
本文介绍了三种类型的循环(For、ForEach、While)的应用场景与实例,以及如何使用数组来存储相似的变量。
706

被折叠的 条评论
为什么被折叠?



