2012-07-09 6 views

Respuesta

14

CoffeeScript tiene for ... by para ajustar el tamaño del paso de un rizo for. Así iterar sobre la matriz en pasos de 2 y apoderarse de sus elementos utilizando un índice:

a = [ 1, 2, 3, 4 ] 
for e, i in a by 2 
    first = a[i] 
    second = a[i + 1] 
    # Do interesting things here 

Demostración: http://jsfiddle.net/ambiguous/pvXdA/

Si lo desea, puede utilizar una asignación desestructurado combinado con una rodaja de matriz dentro del bucle:

a = [ 'a', 'b', 'c', 'd' ] 
for e, i in a by 2 
    [first, second] = a[i .. i + 1] 
    #... 

demostración: http://jsfiddle.net/ambiguous/DaMdV/

también podría omitir la variable ignorado y utilizar un bucle rango:

# three dots, not two 
for i in [0 ... a.length] by 2 
    [first, second] = a[i .. i + 1] 
    #... 

Demostración: http://jsfiddle.net/ambiguous/U4AC5/

que compila a un bucle for(i = 0; i < a.length; i += 2) como todo el resto no lo que el rango no le cuesta nada

+1

Muy informativo.. CoffeeScript es un lenguaje tan hermoso si haces uso de todo su potencial. –

Cuestiones relacionadas