NotDan
NotDan

Reputation: 32223

How to do a for loop with subtraction in CoffeeScript?

How do I write this for loop in CoffeeScript?

for(i = cc.length - 2, i >= 0, i -= 2)

Upvotes: 1

Views: 865

Answers (2)

Trevor Burnham
Trevor Burnham

Reputation: 77416

for i in [cc.length - 2..0] by -2
  ...

Compilation here. The by keyword isn't very well-known, but it's invaluable.

One caveat: You have to remember to do the range backward (upper..0). And you cannot iterate through an array backward with this approach:

for i in arr by -1  # infinite loop!

Upvotes: 5

mpm
mpm

Reputation: 20155

i = cc.length-2
while  i>=0
  #code
  i-=2

Upvotes: 3

Related Questions