CoffeeScript - 循环

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

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

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

Loop Architecture

JavaScript提供,而 for..in 循环. CoffeeScript中的循环类似于JavaScript中的循环.

循环及其变体是CoffeeScript中唯一的循环结构. CoffeeScript不是常用的 for 循环,而是为您提供理解,这些内容将在后面的章节中详细讨论.

while循环CoffeeScript

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

语法

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

while expression
   statements to be executed

示例

以下示例演示了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"

打开命令提示符并编译.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);

现在,再次打开命令提示符并运行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

while的变体

CoffeeScript中的While循环有两个变体,即直到变体循环变体.

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

while 变量 while 循环包含布尔表达式和块代码只要给定的布尔表达式为假,就会执行此循环的代码块.

2loop variant of while

循环 variant等同于 while 循环,其值为真(真实).这个循环中的语句将重复执行,直到我们使用 Break 语句退出循环.