CoffeeScript has a for ... by
to adjust the step size of a normal for
loop. So, iterating over the array with step 2 and capturing elements using the index:
a = [ 1, 2, 3, 4 ] for e, i in a by 2 first = a[i] second = a[i + 1]
Demo: http://jsfiddle.net/ambiguous/pvXdA/
If you want, you can use destructive assignment in combination with slice of the array inside the loop:
a = [ 'a', 'b', 'c', 'd' ] for e, i in a by 2 [first, second] = a[i .. i + 1]
Demo: http://jsfiddle.net/ambiguous/DaMdV/
You can also skip the ignored variable and use a range loop:
# three dots, not two for i in [0 ... a.length] by 2 [first, second] = a[i .. i + 1]
Demo: http://jsfiddle.net/ambiguous/U4AC5/
This compilation in a for(i = 0; i < a.length; i += 2)
loop for(i = 0; i < a.length; i += 2)
, like everyone else, so the range does not cost you anything.
source share