目录

while循环变体(loop variant of while)

loop变量等同于具有真值的while循环( while true )。 这个循环中的语句将重复执行,直到我们使用break语句退出循环。

语法 (Syntax)

下面给出了CoffeeScript中while循环的循环替代语法。

loop
   statements to be executed repeatedly
   condition to exit the loop

例子 (Example)

以下示例演示了CoffeeScript中until循环的用法。 这里我们使用Math函数random()生成随机数,如果生成的数字是3,我们使用break语句退出循环。 将此代码保存在名为until_loop_example.coffee的文件中

loop
   num = Math.random()*8|0
   console.log num
   if num == 5 then break

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c loop_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var num;
  while (true) {
    num = Math.random() * 8 | 0;
    console.log(num);
    if (num === 5) {
      break;
    }
  }
}).call(this);

现在,再次打开command prompt并运行Coffee Script文件,如下所示。

c:\> coffee loop_example.coffee

执行时,CoffeeScript文件生成以下输出。

2
0
2
3
7
4
6
2
0
1
4
6
5
↑回到顶部↑
WIKI教程 @2018