From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../reference/statements/while/index.html | 101 +++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/statements/while/index.html (limited to 'files/zh-cn/web/javascript/reference/statements/while') diff --git a/files/zh-cn/web/javascript/reference/statements/while/index.html b/files/zh-cn/web/javascript/reference/statements/while/index.html new file mode 100644 index 0000000000..2faf378422 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/statements/while/index.html @@ -0,0 +1,101 @@ +--- +title: while +slug: Web/JavaScript/Reference/Statements/while +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/while +--- +
{{jsSidebar("Statements")}}
+ +

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

+ +
{{EmbedInteractiveExample("pages/js/statement-while.html")}}
+ + + +

语法

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

示例

+ +

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

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

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

+ + + +

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

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-while-statement', 'while statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.6.2', 'while statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.6.2', 'while statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.6.1', 'while statement')}}{{Spec2('ES1')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.statements.while")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf