JavaScript 中的 For、While 和 Do While 循环(含示例)

如何使用循环?

当您需要重复执行相同的代码行,执行特定次数或只要某个特定条件为真时,循环就非常有用。假设您想在网页上重复输入“Hello”消息 100 次。当然,您必须复制粘贴相同的行 100 次。但是,如果您使用循环,则只需 3 到 4 行即可完成此任务。

Use Loops in Javascript

不同类型的循环

JavaScript 中主要有四种类型的循环。JavaScript.

  1. for 循环
  2. for/in 循环(稍后解释)
  3. while 循环
  4. do…while 循环

for 循环

语法

for(statement1; statement2; statment3)
{
lines of code to be executed
}
  1. 语句 1 在执行循环代码之前执行。因此,此语句通常用于为将在循环内使用的变量赋值。
  2. 语句 2 是执行循环的条件。
  3. 语句 3 在每次循环代码执行后执行。

自己尝试一下

<html>
<head>
	<script type="text/javascript">
		var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
		document.write("<b>Using for loops </b><br />");
		for (i=0;i<students.length;i++)
		{
		document.write(students[i] + "<br />");
		}
	</script>
</head>
<body>
</body>
</html>

while 循环

语法

while(condition)
{
lines of code to be executed
}

只要指定的条件为真,就会执行“while 循环”。在 while 循环内部,您应该包含一个将在某个时候终止循环的语句。否则,您的循环将永远不会结束,并且您的浏览器可能会崩溃。

自己尝试一下

<html>
<head>
	<script type="text/javascript">
		document.write("<b>Using while loops </b><br />");
		var i = 0, j = 1, k;
		document.write("Fibonacci series less than 40<br />");
		while(i<40)
		{
			document.write(i + "<br />");
			k = i+j;
			i = j;
			j = k;
		}
	</script>
</head>
<body>
</body>
</html>

do…while 循环

语法

do
{
block of code to be executed
} while (condition)

do…while 循环与 while 循环非常相似。唯一的区别是,在 do…while 循环中,代码块会在检查条件之前执行一次。

自己尝试一下

<html>
<head>
	<script type="text/javascript">
		document.write("<b>Using do...while loops </b><br />");
		var i = 2;
		document.write("Even numbers less than 20<br />");
		do
		{
			document.write(i + "<br />");
			i = i + 2;
		}while(i<20)
	</script>
</head>
<body>
</body>
</html>