目录

if statement

if语句是基本控制语句,允许我们有条件地做出决策和执行语句。

CoffeeScript中的if语句与我们在JavaScript中的类似。 不同之处在于,在CoffeeScript中编写if语句时,不需要使用括号来指定布尔条件。 另外,我们使用适当的缩进来代替花括号,而是将条件语句的主体分开。

语法 (Syntax)

下面给出了CoffeeScript中if语句的语法。 它包含一个关键字if ,在if关键字之后不久,我们必须指定一个布尔表达式,后跟一个语句块。 如果给定的表达式为true ,则执行if块中的代码。

if expression
   Statement(s) to be executed if expression is true

流程图 (Flow Diagram)

如果声明

例子 (Example)

以下示例演示如何在CoffeeScript中使用if语句。 将此代码保存在名为if_example.coffee的文件中

name = "Ramu"
score = 60
if score>=40
  console.log "Congratulations you have passed the examination"

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c if_example.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var name, score;
  name = "Ramu";
  score = 60;
  if (score >= 40) {
    console.log("Congratulations you have passed the examination");
  }
}).call(this);

现在,再次打开command prompt并运行CoffeeScript文件,如下所示。

c:\> coffee if_example.coffee

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

Congratulations you have passed the examination
↑回到顶部↑
WIKI教程 @2018