unless-then...else 語句



unless-then 語句後面可以根據需要跟一個 else 語句,該語句在布林表示式為 true 時執行。利用 unless-then...else 語句,我們可以在一行中編寫 unless...else 語句。

語法

下面是 CoffeeScript 中 unless-then else 語句的語法。

unless expression then Statements (for false) else Statements (for true)

示例

下面是 CoffeeScript 中 unless-then else 語句的示例。將以下示例儲存在名為unless_then_else_example.coffee 的檔案中

name = "Ramu"
score = 60
unless score>=40 then console.log "Sorry try again" else console.log "congratulations."

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

c:\> coffee -c unless_then_else_example.coffee

編譯時會生成以下 JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var name, score;

  name = "Ramu";

  score = 60;

  if (!(score >= 40)) {
    console.log("Sorry try again");
  } else {
    console.log("congratulations.");
  }

}).call(this);

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

c:\> coffee unless_then_else_example.coffee

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

congratulations.
coffeescript_conditionals.htm
廣告
© . All rights reserved.