CoffeeScript教程

CoffeeScript 循环

在编码时,您可能会遇到需要一遍又一遍地执行一段代码的情况。在这种情况下,您可以使用循环语句。
一般来说,语句是按顺序执行的:首先执行函数中的第一条语句,然后是第二条,依此类推。
循环语句允许我们多次执行一个语句或一组语句。下面给出的是大多数编程语言中循环语句的一般形式
循环架构
JavaScript 提供 while、forfor..in 循环。 CoffeeScript 中的循环类似于 JavaScript 中的循环。
while 循环及其变体是 CoffeeScript 中唯一的循环结构。与常用的 for 循环不同,CoffeeScript 为您提供了 理解,后面的章节将详细讨论这些内容。

CoffeeScript 中的 while 循环

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

语法

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

示例

下面的例子演示了 while 循环在CoffeeScript 中的用法。将此代码保存在名为 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 循环有两种变体,即 until 变体loop 变体
循环类型和描述
while 的until 变体
while 循环的 until 变体包含一个布尔表达式和代码块。只要给定的布尔表达式为假,这个循环的代码块就会被执行。
while 的循环变体
loop 变体等效于 while 循环具有真值 (同时为真)。此循环中的语句将重复执行,直到我们使用 Break 语句退出循环。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4