因为...理解(for..in comprehensions)

优质
小牛编辑
121浏览
2023-12-01

for..in理解是CoffeeScript中理解的基本形式。 使用它,我们可以迭代列表或数组的元素。

语法 (Syntax)

假设我们在CoffeeScript中有一个元素数组作为['element1', 'element2', 'element3']那么你可以使用for-in理解来迭代这些元素,如下所示。

for element in ['element1', 'element2', 'element3']
   console.log element

例子 (Example)

以下示例演示了在CoffeeScript中使用for…in comprehension。 将此代码保存在名为for_in_comprehension.coffee的文件中

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

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

c:\> coffee -c for_in_comprehension.coffee

在编译时,它为您提供以下JavaScript。 在这里,您可以观察到理解被转换为for循环。

// Generated by CoffeeScript 1.10.0
(function() {
  var i, len, ref, student;
  ref = ['Ram', 'Mohammed', 'John'];
  <b>for (i = 0, len = ref.length; i < len; i++) {
    student = ref[i];
    console.log(student);
  }</b>
}).call(this);

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

c:\> coffee for_in_comprehension.coffee

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

Ram
Mohammed
John