I want to use every pair of entries in an array. Is there an effective way to do this in CoffeeScript without using the length
property of the array?
I am currently doing something like the following:
# arr is an array
for i in [0...arr.length]
first = arr[i]
second = arr[++i]
CoffeeScript has for ... by
for adjusting the step size of a normal for
loop. So iterate over the array in steps of 2 and grab your elements using an index:
a = [ 1, 2, 3, 4 ]
for e, i in a by 2
first = a[i]
second = a[i + 1]
# Do interesting things here
Demo: http://jsfiddle.net/ambiguous/pvXdA/
If you want, you could use a destructured assignment combined with an array slice 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 could 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/
That compiles to a for(i = 0; i < a.length; i += 2)
loop like all the rest do so the range doesn't cost you anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With