Simple loop in coffeescript

I have this code:

count = $content.find('.post').length; for x in [1...count] /* prev_el_height += $("#content .post:nth-child(" + x + ")").height(); */ prev_el_height += $content.find(".post:nth-child(" + x + ")").height(); 

I expected it to turn into

 for (x = 1; x < count; x++) { prev_el ... } 

but it turns into this:

 for (x = 1; 1 <= count ? x < count : x > count; 1 <= count ? x++ : x--) { 

Can someone explain why?

EDIT: How to get the expected syntax for output?

+8
coffeescript
source share
4 answers

In CoffeeScript, you need to use the by keyword to indicate the step of the loop. In your case:

 for x in [1...count] by 1 ... 
+22
source share

You request a loop from 1 to count , but you assume that count will always be greater than or equal to one; the generated code does not make this assumption.

So, if count is> = 1, then the loop counter is incremented every time:

 for (x = 1; x < count; x++) { /* ... */ } 

But if count 1, then the loop counter decreases every time:

 for (x = 1; x > count; x--) { /* ... */ } 
+3
source share

Well, you want x go from 1 to count . The code checks if count greater or less.

If count greater than 1, then it must increment x while it is less than count .

If count less than 1, then it must decrease x , while it is greater than count .

+2
source share

For future reference:

 $('#content .post').each -> prev_el_height += $(this).height() 

It has the same effect if :nth-child equivalent to .eq() , and x passes the number in which the elements are typos.

0
source share

All Articles