CoffeeScript – while 的 until 變數



CoffeeScript 提供的 until 選項與 while 迴圈正好相反。它包含一個布林表示式和一個程式碼塊。只要給定的布林表示式為假,就會執行 until 迴圈的程式碼塊。

語法

下面給出了 CoffeeScript 中 until 迴圈的語法。

until expression
   statements to be executed if the given condition Is false

示例

以下示例演示了 CoffeeScript 中 until 迴圈的用法。將這段程式碼儲存在名為 until_loop_example.coffee 的檔案中。

console.log "Starting Loop "
count = 0  
until count > 10
   console.log "Current Count : " + count
   count++;
   
console.log "Set the variable to different value and then try"

開啟 命令提示符 並編譯 .coffee 檔案,如下所示。

c:\> coffee -c until_loop_example.coffee

編譯後,會給你以下 JavaScript。在這裡,你可以看到 until 迴圈在生成的 JavaScript 程式碼中被轉換成 while not

// Generated by CoffeeScript 1.10.0
(function() {
  var count;

  console.log("Starting Loop ");

  count = 0;

  while (!(count > 10)) {
    console.log("Current Count : " + count);
    count++;
  }

  console.log("Set the variable to different value and then try");

}).call(this);

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

c:\> coffee until_loop_example.coffee

執行後,CoffeeScript 檔案將產生以下輸出。

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Set the variable to different value and then try 
coffeescript_loops.htm
廣告
© . All rights reserved.