目录

if...else statement

if指定的布尔表达式为true, if语句执行给定的代码块。 如果布尔表达式为假,该怎么办?

'if...else'语句是控制语句的下一种形式,它允许CoffeeScript以更加可控的方式执行语句。 它将有一个else块,当布尔表达式为false时执行。

语法 (Syntax)

下面给出了CoffeeScript中if-else语句的语法。 如果给定的表达式为true,则执行if块中的语句,如果为false,则执行else块中的语句。

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

流程图 (Flow Diagram)

if else声明

例子 (Example)

以下示例演示如何在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"

打开command prompt并编译.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);

现在,再次打开command prompt并运行CoffeeScript文件 -

c:\> coffee if_else_example.coffee

执行时,CoffeeScript文件生成以下输出。

Sorry try again
↑回到顶部↑
WIKI教程 @2018