现在的位置: 首页 > 综合 > 正文

JS For 循环

2013年10月20日 ⁄ 综合 ⁄ 共 1694字 ⁄ 字号 评论关闭

Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
在JS中的循环用来重复执行指定次数的代码或当条件为真时重复执行。


Examples
例 子

For loop[for循环]
How to write a for loop. Use a For loop to run the same block of code a specified number of times.
怎样写一段循环。使用循环来执行指定次数的相同代码块

Looping through HTML headers[循环的HTML标题]
How to use the for loop to loop through the different HTML headers.
怎样使用for循环来完成不同样子的HTML标题


JavaScript Loops
JS 循环

Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
当你写代码的时候会经常要让一段代码一行行的重复执行,要完成这样的任务不需要你添加重复的代码,我们只要使用循环就行。

In JavaScript there are two different kind of loops:
在JS中有两种循环:

  • for - loops through a block of code a specified number of times
    for - 次数循环
  • while - loops through a block of code while a specified condition is true
    while - 条件循环

The for Loop
for循环

The for loop is used when you know in advance how many times the script should run.
使用for循环一般是当你事先知道脚本应该执行几次。

Syntax
语法

for (var=startvalue;var<=endvalue;var=var+increment) 
{
code to be executed

}

Example
例子

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
释义:下面的例子定义了一个开始i=0的循环.循环会一直运行下去直到i大于10.i每次循环会递增1

Note: The increment parameter could also be negative, and the <= could be any comparing statement.
注意:递增的参数还可以是递减的,<=是可以换成其他的任何操作符。

<html>
<body>
<script type="text/javascript">

var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>

Result
(运行后的结果为)

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10


The while loop
while loop循环语句

The while loop will be explained in the next chapter.
while / loop  循环语句将在下一章作具体讲解。

 

抱歉!评论已关闭.