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

JavaScript
JS数学对象参考
JS字符串对象参考
JS函数参考
JS事件参考
Javascript 常用正则表达式
FF和IE下的js兼容性问题
jQuery 简单介绍
jQuery / 核心 / $(expression, [context] ) 函数
jQuery / 核心 / $(html) 函数
如何使用JS来判断浏览器类型(ie、firefox,等等)
Javascript在IE和FireFox中的不同表现
3个js字符编码函数区别
javascript 中的 XMLDOM 对象

JavaScript 中的 JS While 循环


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-01   浏览: 1285 ::
收藏到网摘: 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
举例

While loop
How to write a while loop. Use a while loop to run the same block of code while a specified condition is true.
演示怎样写一段while循环

Do while loop
How to write a do...while loop. Use a do...while loop to run the same block of code while a specified condition is true. This loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested.
写do...while循环,(效果和上面的差不多,条件为假的时候也会执行一次,这就是区别,因为判断在执行之后,具体的看连接里的实例)


The while loop
while循环

The while loop is used when you want the loop to execute and continue executing while the specified condition is true. 
当条件持续为真的时候循环执行相同的代码, 这就是while循环的用途

while (var<=endvalue)
{ code to be executed
}

Note: The <= could be any comparing statement.
注意:<=可以比较任何申明(我的理解是不光可以比较数字类型,字符也可以比较)

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。

<html>
<body>
<script type="text/javascript">
var i=0
while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
</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 do...while Loop
do...while循环

The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.
do...whlie是另外一种形式的while循环。条件判断在执行之后

do
{ code to be executed
}
while (var<=endvalue)

Example
例子

<html>
<body>
<script type="text/javascript">
var i=0
do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0)
</script>
</body>
</html>

Result
(运行后的结果)

The number is 0

评论 (1) 1 All

登陆 | 还没注册?