Coffeescript-if-then-else-statement-in-coffeescript

提供:Dev Guides
移動先:案内検索

CoffeeScript-if-then …​ elseステートメント

if-thenステートメントの後にオプションの else ステートメントを続けることができます。これは、ブール式がfalseの場合に実行されます。 if-then …​ elseステートメントを使用して、if …​ elseステートメントを1行で記述できます。

構文

以下は、CoffeeScriptの if-then …​ else ステートメントの構文です。

if expression then Statements (for true condition) else Statements (for false condition)

以下は、CoffeeScriptの if-then …​ else ステートメントの例です。 このコードを if_then_else_example.coffee という名前のファイルに保存します

name = "Ramu"
score = 30
if score>=40 then console.log "Congratulations" else console.log "Sorry try again"
  • コマンドプロンプト*を開き、以下に示すように.coffeeファイルをコンパイルします。
c:\> coffee -c if_then_else_example.coffee

コンパイル時に、次のJavaScriptが提供されます。

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

  name = "Ramu";

  score = 30;

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

}).call(this);

ここで、*コマンドプロンプト*を再度開き、CoffeeScriptファイルを次のように実行します-

c:\> coffee if_then_else_example.coffee

CoffeeScriptファイルを実行すると、次の出力が生成されます。

Sorry try again