CoffeeScript – 迴圈變種 while



迴圈變種等同於 true 值(while true)的 while 迴圈。此迴圈中的語句將在我們使用 break 語句退出迴圈之前重複執行。

語法

以下是 CoffeeScript 中 while 迴圈迴圈備選方案的語法。

loop
   statements to be executed repeatedly
   condition to exit the loop

示例

以下示例演示了在 CoffeeScript 中使用 until 迴圈。此處我們使用了 math 函式 random() 生成隨機數,如果生成的數為 3,我們便使用 break 語句退出迴圈。將此程式碼儲存在名為 until_loop_example.coffee 的檔案中

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

開啟命令提示符並編譯 .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);

現在,再次開啟命令提示符並執行 Coffee Script 檔案,如下所示。

c:\> coffee loop_example.coffee

執行後,CoffeeScript 檔案會生成以下輸出。

2
0
2
3
7
4
6
2
0
1
4
6
5
coffeescript_loops.htm
廣告
© . All rights reserved.