JavaScript学习与实践(9)
例子:
FOR LOOP 用它来执行特定次数的同一代码
<html>
<body>
<script type="text/javascript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
<p>Explanation:</p>
<p>This for loop starts with i=0.</p>
<p>As long as <b>i</b> is less than, or equal to 5, the loop will continue to run.</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
</body>
</html>
执行的结果在下面
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Explanation:
This for loop starts with i=0.
As long as i is less than, or equal to 5, the loop will continue to run.
i will increase by 1 each time the loop runs.
下面一个例子就是用循环来给出头字号大小不一样的做法
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
}
</script>
</body>
</html>
执行结果在下面,
This is header 1
This is header 2
This is header 3
This is header 4
This is header 5
This is header 6
循环在写JS中是很常用的,The FOR LOOP 这个循环是你知道这个循环要执行多少次的时候来用,
语法:
for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed }
while 循环
怎么写一个while 循环,当满足特定条件才开始执行循环,不满足的时候就跳出,
<html>
<body>
<script type="text/javascript">
i = 0
while (i <= 5)
{
document.write("The number is " + i)
document.write("<br>")
i++
}
</script>
<p>Explanation:</p>
<p><b>i</b> is equal to 0.</p>
<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
</body>
</html>
DO....WHILE循环,这个循环是不管你满足不满足条件就是先执行了一边再去判断满足不满足特定的条件,知道不满足就跳出
<html>
<body>
<script type="text/javascript">
i = 0
do
{
document.write("The number is " + i)
document.write("<br>")
i++
}
while (i <= 5)
</script>
<p>Explanation:</p>
<p><b>i</b> equal to 0.</p>
<p>The loop will run</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
</body>
</html>