目录

CoffeeScript - 循环

编码时,您可能会遇到需要反复执行代码块的情况。 在这种情况下,您可以使用循环语句。

通常,语句按顺序执行:首先执行函数中的第一个语句,然后执行第二个语句,依此类推。

循环语句允许我们多次执行语句或语句组。 下面给出的是大多数编程语言中循环语句的一般形式

循环架构

JavaScript提供while, forfor..in循环。 CoffeeScript中的循环与JavaScript中的循环类似。

while循环及其变体是CoffeeScript中唯一的循环结构。 CoffeeScript不是常用的for循环,而是为您提供在后面的章节中详细讨论的Comprehensions

CoffeeScript中的while循环

while循环是CoffeeScript提供的唯一低级循环。 它包含一个布尔表达式和一个语句块。 只要给定的布尔表达式为真, while循环就会重复执行指定的语句块。 表达式变为false后,循环终止。

语法 (Syntax)

以下是CoffeeScript中while循环的语法。 这里,没有必要使用括号来指定布尔表达式,我们必须使用(一致数量的)空格缩进循环体,而不是用花括号包装它。

while <b class="notranslate">expression</b>
   statements to be executed

例子 (Example)

以下示例演示了CoffeeScript中while循环的用法。 将此代码保存在名为while_loop_example.coffee的文件中

console.log "Starting Loop "
count = 0  
while count < 10
   console.log "Current Count : " + count
   count++;
console.log "Set the variable to different value and then try"

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

c:\> coffee -c while_loop_example.coffee

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

// Generated by CoffeeScript 1.10.0
(function() {
  var count;
  console.log("Starting Loop ");
  count = 0;
  while (count < 10) {
    console.log("Current Count : " + count);
    count++;
  }
  console.log("Set the variable to different value and then try");
}).call(this); 

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

c:\> coffee while_loop_example.coffee

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

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Set the variable to different value and then try 

变异的同时

CoffeeScript中的While循环有两个变体,即until variantloop variant

S.No. 循环类型和描述
1 until variant of while

while循环的until变量包含一个布尔表达式和一个代码块。 只要给定的布尔表达式为false,就执行此循环的代码块。

2 while循环变体

loop变量等同于具有真值的while循环(while true) 。 这个循环中的语句将重复执行,直到我们使用Break语句退出循环。

↑回到顶部↑
WIKI教程 @2018