CoffeeScript - unless..then 語句



使用 unless-then 語句,我們可以用單行書寫 CoffeeScript 中的 unless 語句。它由一個布林表示式和一個 then 關鍵字組成,其後面跟隨一個或多個語句。當給定的布林表示式為假時,這些語句執行。

語法

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

unless expression then Statement(s) to be executed if expression is false

示例

以下是 CoffeeScript unless-then 語句的示例。將以下示例儲存到名為 unless_then_example.coffee 的檔案中

name = "Ramu"
score = 30
unless score>=40 then console.log "Sorry try again"

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

c:\> coffee -c unless_then_example.coffee

編譯後,它會輸出以下 JavaScript。

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

  name = "Ramu";

  score = 30;

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

}).call(this);

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

c:\> coffee unless_then_example.coffee

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

Sorry try again
coffeescript_conditionals.htm
廣告