减少咖啡脚本中的循环 [英] Decrementing for loop in coffeescript

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

问题描述

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

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

咖啡脚本:

for some in something

生成的 Javascript:

Generated Javascript:

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

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

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

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

推荐答案

从 CoffeeScript 1.5 开始支持 by -1 语法.

As of CoffeeScript 1.5 by -1 syntax is supported.

首先,您应该熟悉 by 关键字,它可以让您指定一个步骤.其次,您必须了解 CoffeeScript 编译器采用非常幼稚的方法来循环端点(请参阅 issue1187,Blender 链接到的),这意味着

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!!!

将导致无限循环——它从索引 0 开始,将索引递增 -1,然后等待索引到达 something.length.叹息.

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]

显然这很混乱.因此,您应该强烈考虑迭代 something.reverse() .请记住,reverse() 会修改您调用它的数组!如果你想保留一个数组但向后迭代它,你应该复制它:

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()

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

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