CoffeeScript - if...else 語句



如果指定的布林表示式為真,if 語句將執行給定的程式碼塊。如果布林表示式為假,怎麼辦?

‘if...else’ 語句是另一種控制語句形式,它允許 CoffeeScript 以更可控的方式執行語句。它將有一個 else 塊,當布林表示式為 時執行。

語法

以下是 CoffeeScript 中 if-else 語句的語法。如果給定的表示式為真,則執行 if 塊中的語句;如果為假,則執行 else 塊中的語句。

if expression
   Statement(s) to be executed if the expression is true
else
   Statement(s) to be executed if the expression is false

流程圖

if else statement

示例

以下示例演示如何在 CoffeeScript 中使用 if-else 語句。將此程式碼另存為名為 if_else_example.coffee 的檔案中

name = "Ramu"
score = 30
if score>=40
  console.log "Congratulations have passed the examination"
else 
  console.log "Sorry try again"

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

c:\> coffee -c if_else_example.coffee

編譯後,它會生成以下 JavaScript。

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

  name = "Ramu";

  score = 30;

  if (score >= 40) {
    console.log("Congratulations have passed the examination");
  } else {
    console.log("Sorry try again");
  }

}).call(this);

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

c:\> coffee if_else_example.coffee

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

Sorry try again
coffeescript_conditionals.htm
廣告
© . All rights reserved.