当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JS For 循环

JavaScript
JS 介绍
JS 怎样使用
JS 在哪使用
JS 变量
JS If...Else
JS Switch
JS 操作符
JS Popup Boxes
JS 函数
JS For 循环
JS While 循环
JS Break 循环
JS For...In
JS 事件
JS Try...Catch
JS Throw
JS onerror
JS 特殊字符
JS Guidelines
JS 对象介绍

JavaScript 中的 JS For 循环


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-01   浏览: 1316 ::
收藏到网摘: n/a

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  循环语句将在下一章作具体讲解。

评论 (1) 1 All

登陆 | 还没注册?