Coffeescript-unless-else-statement-in-coffeescript

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

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

*if else* ステートメントと同様に、CoffeeScriptにも *unelse else* ステートメントがあります。 ブール式、 *unless* ブロック、 *else* ブロックが含まれます。 指定された式が *false* の場合、 *unless* ブロックが実行され、trueの場合、 *else* ブロックが実行されます。

構文

以下に、CoffeeScriptの unelse else ステートメントの構文を示します。

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

流れ図

elseステートメントがない限り

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