从CoffeeScript中的数组中获取每两个元素

knp*_*wrs 6 coffeescript

我想使用数组中的每对条目.有没有一种有效的方法在CoffeeScript中执行此操作而不使用length数组的属性?

我目前正在做类似以下的事情:

# arr is an array
for i in [0...arr.length]
    first = arr[i]
    second = arr[++i]
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 14

CoffeeScript for ... by用于调整正常for循环的步长.因此,以2为步长迭代数组并使用索引获取元素:

a = [ 1, 2, 3, 4 ]
for e, i in a by 2
    first  = a[i]
    second = a[i + 1]
    # Do interesting things here
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/pvXdA/

如果需要,可以在循环内使用结构化赋值和数组切片:

a = [ 'a', 'b', 'c', 'd' ]
for e, i in a by 2
    [first, second] = a[i .. i + 1]
    #...
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/DaMdV/

您还可以跳过忽略的变量并使用范围循环:

# three dots, not two
for i in [0 ... a.length] by 2
    [first, second] = a[i .. i + 1]
    #...
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/U4AC5/

编译成一个for(i = 0; i < a.length; i += 2)循环就像其他所有这样做,范围不会花费你任何东西.