Coffeescript 简明教程

CoffeeScript - Comprehensions

在上一个章节中,我们了解了 CoffeeScript 提供的各种循环、 while 及其变体。除此之外,CoffeeScript 还提供了称为 comprehensions 的附加循环结构。

In the previous chapter, we have learnt various loops provided by CoffeeScript, while and its variants. In addition to those, CoffeeScript provides additional loop structures known as comprehensions.

如果我们添加可选的保护子句和当前数组索引的值,这些列表解析会替换其他编程语言中的 for 循环。使用列表解析,我们可以遍历数组和对象,而遍历数组的列表解析是表达式,而且我们可以在函数中返回它们或将它们分配给变量。

These comprehensions replace the for loop in other programming languages, if we add the optional guard clauses and the value of the current array index explicitly. Using comprehensions, we can iterate arrays as well as objects and the comprehensions that iterate arrays are expressions, and we can return them in a function or assign to a variable.

S.No.

Statement & Description

1

for..in comprehensionsThe for..in comprehension is the basic form of comprehension in CoffeeScript using this we can iterate the elements of a list or array.

2

for..of comprehensionsJust like Arrays CoffeeScriptScript provides a containers to store key-value pairs known as objects. We can iterate objects using the for..of comprehensions provided by CoffeeScript.

3

list comprehensionsThe list comprehensions in CoffeeScript are used to map an array of objects to another array.

Index of comprehensions

元素列表/数组有一个索引,可以在列表解析中使用。您可以使用变量在列表解析中使用它,如下所示:

The list/array of elements have an index which can be used in comprehensions. You can use it in comprehensions using a variable as shown below.

for student,i in [element1, element2, element3]

Example

以下示例演示了在 CoffeeScript 中使用 for…in 理解的索引。将以下代码保存在一个名叫 for_in_index.coffee 的文件中

The following example demonstrates the usage of index of the for…in comprehension in CoffeeScript. Save this code in a file with name for_in_index.coffee

for student,i in ['Ram', 'Mohammed', 'John']
   console.log "The name of the student with id "+i+" is: "+student

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c for_in_index.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var i, j, len, ref, student;

  ref = ['Ram', 'Mohammed', 'John'];
  for (i = j = 0, len = ref.length; j < len; i = ++j) {
    student = ref[i];
    console.log("The name of the student with id " + i + " is: " + student);
  }
}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee for_in_index.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

The name of the student with id 0 is: Ram
The name of the student with id 1 is: Mohammed
The name of the student with id 2 is: John

Postfix form of comprehensions

与后缀 ifunless 类似,CoffeeScript 提供了理解的后缀形式,在编写代码时非常方便。使用此功能,我们可以在单行中编写 for..in 理解,如下所示。

Just like postfix if and unless, CoffeeScript provides the postfix form of the Comprehensions which comes handy while writing the code. Using this, we can write the for..in comprehension in a single line as shown below.

#Postfix for..in comprehension
console.log student for student in ['Ram', 'Mohammed', 'John']

#postfix for..of comprehension
console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}

Assigning to a variable

我们用于遍历数组的理解可以赋值给变量,也可以由函数返回。

The comprehension we use to iterate arrays can be assigned to a variable and also returned by a function.

Example

考虑以下示例。在这里,您可以观察到我们使用 for..in 理解检索了数组的元素,并将其赋给名为 names 的变量。我们还拥有一个函数,该函数使用 return 关键字明确返回理解。将以下代码保存在一个名叫 example.coffee 的文件中

Consider the example given below. Here you can observe that we have retrieved the elements of an array using for..in comprehension and assigned this to a variable named names. And we also have a function which returns a comprehension explicitly using the return keyword. Save this code in a file with name example.coffee

my_function =->
   student = ['Ram', 'Mohammed', 'John']

   #Assigning comprehension to a variable
   names = (x for x in student )
   console.log "The contents of the variable names are ::"+names

   #Returning the comprehension
   return x for x in student
console.log "The value returned by the function is "+my_function()

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var my_function;

  my_function = function() {
    var i, len, names, student, x;
    student = ['Ram', 'Mohammed', 'John'];
    names = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = student.length; i < len; i++) {
        x = student[i];
        results.push(x);
      }
      return results;
    })();
    console.log("The contents of the variable names are ::" + names);
    for (i = 0, len = student.length; i < len; i++) {
      x = student[i];
      return x;
    }
  };

  console.log("The value returned by the function is " + my_function());

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

The contents of the variable names are ::Ram,Mohammed,John
The value returned by the function is Ram

The by keyword

CoffeeScript 提供范围来定义元素列表。例如,范围 [1..10] 等同于 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],其中的每个元素都会增加 1。我们还可以使用理解的 by 关键字更改此增量。

CoffeeScript provides ranges to define a list of elements. For example, the range [1..10] is equivalent to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] where, every element is incremented by 1. We can also change this increment using the by keyword of comprehensions.

Example

以下示例演示了 CoffeeScript 提供的 for..in 理解的 by 关键字的使用。将以下代码保存在一个名叫 by_keyword_example.coffee 的文件中

The following example demonstrates the usage of the by keyword of the for..in comprehension provided by CoffeeScript. Save this code in a file with name by_keyword_example.coffee

array = (num for num in [1..10] by 2)
console.log array

打开 command prompt 并按照以下所示编译 .coffee 文件。

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c by_keyword_example.coffee

编译后,它会给你以下 JavaScript。

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var array, num;

  array = (function() {
    var i, results;
    results = [];
    for (num = i = 1; i <= 10; num = i += 2) {
      results.push(num);
    }
    return results;
  })();

  console.log(array);

}).call(this);

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

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee by_keyword_example.coffee

执行后,CoffeeScript 文件产生以下输出。

On executing, the CoffeeScript file produces the following output.

[ 1, 3, 5, 7, 9 ]