CoffeeScript - 迴圈



在編寫程式碼時,您可能會遇到需要反覆執行程式碼塊的情況。在這種情況下,您可以使用迴圈語句。

通常,語句按順序執行:函式中的第一個語句首先執行,然後是第二個語句,依此類推。

迴圈語句允許我們多次執行一個語句或一組語句。下面是大多數程式語言中迴圈語句的一般形式

Loop Architecture

JavaScript 提供了 **while**、**for** 和 **for..in** 迴圈。CoffeeScript 中的迴圈類似於 JavaScript 中的迴圈。

**while** 迴圈及其變體是 CoffeeScript 中唯一的迴圈結構。CoffeeScript 沒有使用常見的 **for** 迴圈,而是提供了 **推導式**,將在後面的章節中詳細討論。

CoffeeScript 中的 while 迴圈

**while** 迴圈是 CoffeeScript 提供的唯一低階迴圈。它包含一個布林表示式和一個語句塊。**while** 迴圈重複執行指定的語句塊,只要給定的布林表示式為真。一旦表示式變為假,迴圈就會終止。

語法

以下是 CoffeeScript 中 **while** 迴圈的語法。這裡不需要使用括號來指定布林表示式,並且我們必須使用(一致數量的)空格縮排迴圈體,而不是用大括號將其括起來。

while expression
   statements to be executed

示例

以下示例演示了在 CoffeeScript 中使用 **while** 迴圈。將此程式碼儲存到名為 **while_loop_example.coffee** 的檔案中

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"

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

c:\> coffee -c while_loop_example.coffee

編譯後,它會為您提供以下 JavaScript。

// 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); 

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

c:\> coffee while_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 

while 的變體

CoffeeScript 中的 While 迴圈有兩個變體,即 **until 變體** 和 **loop 變體**。

序號 迴圈型別和描述
1 while 的 until 變體

**while** 迴圈的 **until** 變體包含一個布林表示式和一個程式碼塊。只要給定的布林表示式為假,就會執行此迴圈的程式碼塊。

2 while 的 loop 變體

**loop** 變體等效於具有真值 **(while true)** 的 **while** 迴圈。此迴圈中的語句將重複執行,直到我們使用 **Break** 語句退出迴圈。

廣告