CoffeeScript - if-then 語句



使用 if-then 語句,我們可以在 CoffeeScript 的單一語句中編寫 if 語句。它由布林表示式後跟 then 關鍵字組成,然後是若干個語句。當給定的布林表示式為 true 時,會執行這些語句。

語法

CoffeeScript 中 if-then 語句的語法如下。

if expression then Statement(s) to be executed if expression is true

示例

以下是 CoffeeScript 中 if-then 語句的示例。將以下程式碼儲存到名為 if_then_example.coffee 的檔案中

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

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

c:\> coffee -c if_then_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 if_then_example.coffee

執行 CoffeeScript 檔案後,會輸出以下結果。

Congratulations you have passed the exam
coffeescript_conditionals.htm
廣告