Menu Close

JavaScript while 循环语句

JavaScript while 循环语句的语法如下:

while (condition) {
  // code
  // so-called "loop body"
}

只要条件为真(truthy),循环体中的代码就会被执行。

JavaScript while 循环语句
JavaScript while 循环语句

例如,下面的循环会在 i < 3 的情况下输出 i

let i = 0;
while (i < 3) { // shows 0, then 1, then 2
  alert( i );
  i++;
}

对循环体的一次执行称为一次迭代。上面的示例循环进行了三次迭代

如果上面的例子中没有 i++,循环理论上会无限重复。实际上,浏览器提供了停止这种循环的方法,而在服务端 JavaScript 中,我们也可以终止该进程

循环条件可以是任意表达式或变量,不仅仅是比较表达式:while 会对条件进行求值并转换为布尔值。

例如,while (i != 0) 的简写形式是 while (i)

let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
  alert( i );
  i--;
}

如果循环体只有一条语句,我们可以省略花括号 {…}

let i = 3;
while (i) alert(i--);

 

READ  什么是Q# 编程语言?
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!
Posted in JavaScript 基础

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!