simple loop in coffeescript

2020-06-16 03:01发布

问题:

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 this 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 somebody please explain why?

EDIT: How do I get my expected syntax to output?

回答1:

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

for x in [1...count] by 1
  ...


回答2:

You're asking to loop from 1 to count, but you're assuming that count will always be greater-than-or-equal-to one; the generated code doesn't make that assumption.

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

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

But if count is < 1 then the loop counter is decremented each time:

for (x = 1; x > count; x--) { /* ... */ }


回答3:

Well, you want x to go from 1 to count. The code is checking whether count is bigger or smaller than 1.

If count is bigger than 1, then it has to increment x while it is smaller than count.

If count is smaller than 1, then it has to decrement x while it is bigger than count.



回答4:

For future reference:

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

Has the same effect, assuming :nth-child is equivalent to .eq(), and x going past the number the elements is a typo.