Coffeescript-if-else-statement-in-coffeescript

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

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

*if* ステートメントは、指定されたブール式がtrueの場合、指定されたコードブロックを実行します。 ブール式が偽の場合はどうなりますか?
*'if ... else'* ステートメントは、CoffeeScriptがより制御された方法でステートメントを実行できるようにする制御ステートメントの次の形式です。 ブール式が *false* の場合に実行される *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ステートメント

次の例は、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