CoffeeScript for循环获取迭代器var [英] CoffeeScript for loop get iterator var
问题描述
在coffescript中,我有
In coffescript I have
arr = ["a","b","c"]
for i in [0..arr.length] by 1
if (sometimesTrue)
arr.pop()
i--
但它被翻译成:
var arr, i, _i, _ref;
arr = ["a", "b", "c"];
for (i = _i = 0, _ref = arr.length; _i <= _ref; i = _i += 1) {
if (sometimesTrue) {
arr.pop();
i--;
}
}
你可以看到这个循环使用 _i
作为参考而不是 i
,所以我的 i -
t真的做任何事情。
You can see that this loop uses a _i
as the reference rather than i
so my i--
doesn't really do anything.
由于在这个循环中,数组的长度改变,我需要找出如何处理这个...有什么办法做一个for循环?或者我需要切换到一段时间吗?
Since in this loop, the length of the array changes, I sort of need to figure out how to handle this... Is there any way to do this with a for loop? Or do I need to switch to a while?
推荐答案
CoffeeScript将计算循环边界一次,因此在你迭代它的时候改变数组只会产生一个混乱。
CoffeeScript will compute the loop bounds once and you can't reset the calculation so changing the array while you're iterating over it will just make a big mess.
例如:
f(i) for i in [0..a.length]
b $ b
变为:
becomes this:
var i, _i, _ref;
for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
f(i);
}
请注意,当 _ref时,迭代次数是固定的
是在循环开始时计算的。另请注意, i
将在每次迭代中分配一个新值,所以您对 i
被忽略。注意,循环 [0..a.length]
会执行 a.length + 1
迭代, code> a.length 迭代; [a..b]
产生一个封闭间隔(即包含两个端点), [a ... b]
给你一个半开的间隔(即 b
不包括)。类似地,这:
Note that the number of iterations is fixed when _ref
is computed at the beginning of the loop. Also note that i
will be assigned a new value on each iteration so any changes you make to i
inside the loop will be ignored. And, note that looping over [0..a.length]
does a.length+1
iterations, not a.length
iterations; [a..b]
produces a closed interval (i.e. contains both end points), [a...b]
gives you a half-open interval (i.e. b
is not included). Similarly, this:
f(i) for i in a
变为:
var i, _i, _len;
for (_i = 0, _len = a.length; _i < _len; _i++) {
i = a[_i];
f(i);
}
同样,迭代次数是固定的,更改为 i
Again, the number of iterations is fixed and changes to i
are overwritten.
如果你想在循环中搞乱数组和循环索引,那么你必须这样做手动使用和
循环:
If you want to mess around the the array and the loop index inside the loop then you have to do it all by hand using a while
loop:
i = 0
while i < arr.length
if(sometimesTrue)
arr.pop()
--i
++i
或:
i = 0
while i < arr.length
if(sometimesTrue)
arr.pop()
else
++i
这篇关于CoffeeScript for循环获取迭代器var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!