Getting two elements from an array in CoffeeScript

I want to use every pair of records in an array. Is there an efficient 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] 
+6
source share
1 answer

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] # Do interesting things here 

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.

+14
source

Source: https://habr.com/ru/post/919998/


All Articles