Loops coffeescript中循环的递减

Loops coffeescript中循环的递减,loops,for-loop,coffeescript,decrement,Loops,For Loop,Coffeescript,Decrement,我知道如何在coffeescript中执行递增for循环,例如: 咖啡脚本: for some in something 生成的Javascript: for (_i = 0, _len = something.length; _i < _len; _i++) lst = [1,2,3] i = lst.length alert lst[i] while i-- 惯用的方式(从)大致如下: lst = ['a', 'b', 'c'] for n in (num for num in

我知道如何在coffeescript中执行递增for循环,例如:

咖啡脚本:

for some in something
生成的Javascript:

for (_i = 0, _len = something.length; _i < _len; _i++)
lst = [1,2,3]
i = lst.length
alert lst[i] while i--
惯用的方式(从)大致如下:

lst = ['a', 'b', 'c']
for n in (num for num in [lst.length-1..0])
  alert lst[n]
(根据@Trevor的注释编辑)

编辑:

尽管如此,如果性能非常关键,这个等效但可能不那么美观的代码片段将生成更少的javascript:

for (_i = 0, _len = something.length; _i < _len; _i++)
lst = [1,2,3]
i = lst.length
alert lst[i] while i--

似乎没有一种优雅的方法可以反向循环

我检查了GitHub的票证,但它已经关闭:

过去的语法是:

for some in something by -1
但在最近的版本中,它已被删除。
编辑:它现在可以工作了(对于1.6.2@编辑时间)

编辑:从CoffeeScript 1.5开始,支持-1语法。

首先,您应该熟悉
by
关键字,它允许您指定一个步骤。其次,您必须了解CoffeeScript编译器对循环端点采取了一种非常幼稚的方法(请参见链接到哪个混合器),这意味着

for some in something by -1 # don't do this!!!
将导致一个无限循环,它从索引0开始,将索引增加-1,然后等待索引到达
something.length
。唉

因此,您需要使用范围循环语法,它允许您自己指定这些端点,但也意味着您必须自己获取循环项:

for i in [something.length - 1..0] by -1
  some = something[i]
很明显,这很混乱。因此,你应该强烈地考虑迭代<代码>某物。只要记住
reverse()
会修改调用它的数组!如果要保留数组但向后迭代,则应复制它:

for some in something.slice(0).reverse()

一个不同的记录:

i = something.length
while item = something[--i]
  #use item
(将在falsy值上中断)

从coffee脚本开始,支持以下操作:

for item in list by -1
  console.log item
这将转化为

var item, _i;
for (_i = list.length - 1; _i >= 0; _i += -1) {
  item = list[_i];
  console.log(item);
}

对于递减、基于索引的For循环,可以使用:

for i in [0...something.length].reverse()
这消除了所提到的@TrevorBurnham的混乱,这是一个自己指定端点的问题

something.length
0
时,这相当于

for i in []

嗯,这仅在
lst
[1,2,3]
时有效。如果你尝试,比如说,
lst=['a','b','c']
,输出仍然是
3
2
1
。我想你甚至不需要
-1
<代码>在[sth.length-1..0]中为i工作fine@RicardoTomasi您是正确的,它将在没有
by-1
的情况下工作,但是查看编译后的两个输出时效率较低。从编译器的角度来看,
something.length
可能是负数,因此步骤可能是
1
-1
@Robert good catch
在[sth.length-1…-1]
“fixes”中对i进行了如下修改:
数组[…]
数组的简写形式。slice(0)
@davidchambers True,从CoffeeScript 1.3.1开始。您还可以使用
元素,index
语法,例如:
console.log“{item.toString()”,在索引{index}处为item,列表中的索引为-1
此索引在空数组上使用时不会中断