CoffeeScript - 除非...否則語句



就像 if else 語句一樣,CoffeeScript 中也有一個 unless else 語句。它包含布林表示式、一個 unless 塊和一個 else 塊。如果給定表示式為 false,則執行 unless 塊,如果為 true,則執行 else 塊。

語法

以下是 CoffeeScript 中 unless else 語句的語法。

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

流程圖

Unless else statement

示例

以下示例演示了在 CoffeeScript 中使用 unless-else 語句。將此程式碼儲存在一個名為 unless_else_example.coffee 的檔案中

name = "Ramu"
score = 60
unless score>=40
  console.log "Sorry try again"
else
  console.log "Congratulations you have passed the exam"

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

c:\> coffee -c unless_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 you have passed the exam");
  }

}).call(this);

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

c:\> coffee unless_else_example.coffee

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

Congratulations you have passed the exam
coffeescript_conditionals.htm
廣告