CoffeeScript - 字尾 if 和 unless 語句



字尾 if

您可以使用字尾形式重寫 if 語句,其中要執行的語句後跟 if 以及布林表示式。

語法

以下是字尾 if 語句的語法。

Statements to be executed if expression

示例

下面是字尾 if 語句的示例。將以下示例儲存在名為 postfix_if_example.coffee 的檔案中。

name = "Ramu"
score = 60
console.log "Congratulations you have passed the examination" if score>40

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

c:\> coffee -c postfix_if_example.coffee

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

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

  name = "Ramu";

  score = 60;

  if (score > 40) {
    console.log("Congratulations you have passed the examination");
  }

}).call(this);

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

c:\> coffee postfix_if_example.coffee

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

Congratulations you have passed the exam

字尾 unless

您可以使用字尾形式重寫 unless 語句,其中要執行的語句後跟 unless 以及布林表示式。

語法

以下是字尾 if 語句的語法。

Statements to be executed unless expression

示例

下面是字尾 unless 語句的示例。將以下示例儲存在名為 postfix_unless_example.coffee 的檔案中。

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

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

c:\> coffee -c postfix_unless_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  postfix_unless_example.coffee

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

Sorry try again
coffeescript_conditionals.htm
廣告

© . All rights reserved.