while 循环 登录

while 循环

while (条件)
  {
  需要执行的代码;
  }

while

for循环在已知循环的初始和结束条件时非常有用。而上述忽略了条件的for循环容易让人看不清循环的逻辑,此时用while循环更佳。

while循环只有一个判断条件,条件满足,就不断循环,条件不满足时则退出循环。比如我们要计算100以内所有奇数之和,可以用while循环实现:

var x = 0;
var n = 99;
while (n > 0) {
    x = x + n;
    n = n - 2;
}
x; // 2500

在循环内部变量n不断自减,直到变为-1时,不再满足while条件,循环退出。

实例

<!DOCTYPE html>
<html>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
while (i<5)
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
do ... while

最后一种循环是do { ... } while()循环,它和while循环的唯一区别在于,不是在每次循环开始的时候判断条件,而是在每次循环完成的时候判断条件:

var n = 0;
do {
    n = n + 1;
} while (n < 100);
n; // 100

用do { ... } while()循环要小心,循环体会至少执行1次,而for和while循环则可能一次都不执行。

实例

<!DOCTYPE html>
<html>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
do
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
while (i<5)  
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>


下一节
<html> <head> <script> 'use strict'; var arr = ['Bart', 'Lisa', 'Adam']; var i=0; for( i=0;i<arr.length;i++){ alert("hello,"+arr[i]) } while(i<arr.length){ alert("hello,"+arr[i]); i++; } do{ alert("hello,"+arr[i]) i++ }while(i<arr.length) </script> </head> <body> </body> </html>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送