减少coffeescript中的循环 [英] Decrementing for loop in coffeescript

查看:131
本文介绍了减少coffeescript中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何对coffeescript中的循环进行递增,例如:



Coffeescript:

  for some in something 

生成的Javascript:

  for(_i = 0,_len = something.length; _i< _len; _i ++)
pre>

如何在Coffeescript中创建类似于此的递减for循环?

  for(var i = something.length-1; i> = 0; i--)


解决方案

编辑:支持CoffeeScript 1.5 by -1 语法。 >

首先,您应该熟悉关键字,可以指定一个步骤。其次,您必须了解,CoffeeScript编译器对循环端点采用非常朴素的方法(请参见问题1187 ,其中Blender链接到),这意味着

 对于某些东西通过-1#不要这样做! 

将导致无限循环 - 它从索引0开始,将索引递增-1,然后等待直到索引命中 something.length 。 Sigh。



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

  for i in [something.length  -  1..0] by -1 
some = something [i]

显然这很乱。所以你应该强烈地考虑迭代 something.reverse()。只要记住, reverse()修改你调用它的数组!如果你想保留一个数组,但要反向迭代,你应该复制它:

 对于something.slice ).reverse()


I know how to do a incrementing for loop in coffeescript such as:

Coffeescript:

for some in something

Generated Javascript:

for (_i = 0, _len = something.length; _i < _len; _i++)

How do I create a decrementing for loop similar to this in Coffeescript?

for (var i = something.length-1; i >= 0; i--)

解决方案

EDIT: As of CoffeeScript 1.5 by -1 syntax is supported.

First, you should familiarize yourself with the by keyword, which lets you specify a step. Second, you have to understand that the CoffeeScript compiler takes a very naïve approach to loop endpoints (see issue 1187, which Blender linked to), which means that

for some in something by -1 # don't do this!!!

will result in an infinite loop—it starts at index 0, increments the index by -1, and then waits until the index hits something.length. Sigh.

So you need to use the range loop syntax instead, which lets you specify those endpoints yourself—but also means you have to grab the loop items yourself:

for i in [something.length - 1..0] by -1
  some = something[i]

Obviously that's pretty messy. So you should strongly consider iterating over something.reverse() instead. Just remember that reverse() modifies the array that you call it on! If you want to preserve an array but iterate over it backwards, you should copy it:

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

这篇关于减少coffeescript中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆