3

我是 CoffeeScript 的新手,对此非常兴奋。我在这里做了一些基本的循环。现在,CoffeeScript 正在为每个循环定义一个循环变量,如下所示:

var food, _i, _j, _len, _len1;

for (_i = 0, _len = fruits.length; _i < _len; _i++) {
  food = fruits[_i];
  console.log(food);
}

for (_j = 0, _len1 = vegetables.length; _j < _len1; _j++) {
  food = vegetables[_j];
  console.log(food);
}

我曾经这样编写循环代码:

for(var i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

for(var i = 0; i < vegetables.length; i++) {
    console.log(vegetables[i]);
}

i每个循环的循环变量(不包括嵌套循环)。现在我了解到您应该始终在定义变量之前声明它。所以我改变了我的编码习惯:

var i;
for(i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

for(i = 0; i < vegetables.length; i++) {
    console.log(vegetables[i]);
}

只要我在同一个范围内,我就没有发现任何问题,但是编译后的 CoffeeScript 代码让我感到疑惑。

为什么 CoffeeScript 会为每个循环使用不同的变量?

4

2 回答 2

2

在没有查看 CoffeeScript 源代码的情况下,这是我的(受过教育的)猜测:

CoffeeScript 解释器只是为您编写for的每个代码创建一个新的循环结构。for .. in在构建输出 JS 时,它维护一个局部变量名称表,并根据需要附加到该表中。

毕竟,您可以嵌套这些for .. in循环,在这种情况下,无论如何您都需要在 JS 中使用单独的循环变量。

有必要跟踪局部函数范围内的哪些变量可能被重用。这是可能的,但比它的价值更复杂——它根本没有提供任何好处,所以 CoffeeScript 没有这样做。

于 2012-08-14T11:27:25.557 回答
1

The other side of this is, CS can't count on you only using the variable inside of the loop. While it could be dangerous to rely on your iteration variable for use outside the loop, it's possible you will want to. CS reusing it wouldn't give you that chance, if it always used the same variable.

于 2012-08-14T11:52:42.187 回答