首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

while

while 语句可以在某个条件表达式为真的前提下,循环执行指定的一段代码,直到那个表达式不为真时结束循环。

语法

代码语言:javascript
复制
while (condition)
  statement

condition条件表达式,在每次循环前被求值。如果求值为真,statement就会被执行。如果求值为假,则跳出while循环执行后面的语句。statement只要条件表达式求值为真,该语句就会一直被执行。要在循环中执行多条语句,可以使用块语句({ ... })包住多条语句。

注意:使用break语句在condition计算结果为真之前停止循环。

示例

下面的while循环会一直循环若干次直到n等于3

代码语言:javascript
复制
var n = 0;
var x = 0;

while (n < 3) {
  n++;
  x += n;
}

在每次循环中,n都会自增1,然后再把n加到x上。因此,在每轮循环结束后,xn的值分别是:

  • 第一轮后:n = 1,x = 1

  • 第二轮后:n = 2,x = 3

  • 第三轮后:n = 3,x = 6

当完成第三轮循环后,条件表达式n< 3 不再为真,因此循环终止。

规范

Specification

Status

Comment

ECMAScript Latest Draft (ECMA-262)The definition of 'while statement' in that specification.

Living Standard

?

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'while statement' in that specification.

Standard

?

ECMAScript 5.1 (ECMA-262)The definition of 'while statement' in that specification.

Standard

?

ECMAScript 3rd Edition (ECMA-262)The definition of 'while statement' in that specification.

Standard

?

ECMAScript 1st Edition (ECMA-262)The definition of 'while statement' in that specification.

Standard

Initial definition

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com