开发者

How can I convert a JavaScript for-loop to CoffeeScript?

for (i = 0; i < 10; i++) {

    doStuff();

}

That's the JavaScript code that I Want to convert to CoffeeS开发者_如何转开发cript.


doStuff() for i in [0 .. 9]

This is explained on the introduction page: http://coffeescript.org/#loops

Edit/Update by JP:

The exact translation is:

doStuff() for i in [0...10]

You need to be careful with the ".." vs "...", for example:

count = 0
doStuff() for i in [0..count] #still executes once!

So you think, no problem... I'll just loop until count-1!

count = 0
doStuff() for i in [0..count-1] #executes twice!! '0' and then '-1'

Literal translation of:

for (var i = 0; i < someCount; ++i)
  doStuff()

is

for i in [0...someCount]
  doStuff()   


The marked answer is functionaly correct but the generated code doesn't match the original javascript.
The right way (read, the one closest to the following javascript)

for (i = 0; i < 10; i++) {
  doStuff();
}

is doStuff() for i in [0..someCount] by 1 Note the by 1 on the for loop.

Now this code, still creates an extra _i variable. If you can't live with it, then use the following:

i=0
while i<=someCount
  doStuff()
  i++


Previous answers work. However, dropping the i generates it better for me:

for [0...10]
  doStuff()

or

doStuff() for [0...10]

The other solutions add an extra iterator variable i for you to use inside of the loop, for example doStuff(i), but from http://coffeescript.org/v1/#loops:

If you don’t need the current iteration value you may omit it:

browser.closeCurrentTab() for [0...count]

In detail, the translation of for i in [0...10] is for (i = j = 0; j < 10; i = ++j), whereas the translation of for [0...10] is for (i = 0; i < 10; i++).

Note the discussion in other comments about 2-dots versus 3-dots ([0..9] vs. [0...10]).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜