7

菜鸟问题。我正在尝试编写一个带有范围的 for 循环。例如,这是我想用 JavaScript 生成的:

var i, a, j, b, len = arr.length;
for (i = 0; i < len - 1; i++) {
    a = arr[i];
    for (j = i + 1; i < len; j++) {
        b = arr[j];
        doSomething(a, b);
    }
}

到目前为止我最接近的是以下,但是

  1. 它会生成不必要且昂贵的切片调用
  2. 访问内部循环内的数组长度

咖啡脚本:

for a, i in a[0...a.length-1]
    for b, j in a[i+1...a.length]
        doSomething a, b

生成的代码:

var a, b, i, j, _i, _j, _len, _len1, _ref, _ref1;

_ref = a.slice(0, a.length - 1);
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  a = _ref[i];
  _ref1 = a.slice(i + 1, a.length);
  for (j = _j = 0, _len1 = _ref1.length; _j < _len1; j = ++_j) {
    b = _ref1[j];
    doSomething(a, b);
  }
}

(如何)这可以用 CoffeeScript 来表达吗?

4

2 回答 2

10

基本上,将您的第一个 JS 代码转录为 CS:

len = arr.length
for i in [0...len - 1] by 1
  a = arr[i]
  for j in [i + 1...len] by 1
    b = arr[j]
    doSomething a, b
于 2013-02-15T02:43:18.610 回答
1

似乎避免额外变量的唯一方法是使用while循环http://js2.coffee

i = 0
len = arr.length 

while i < len - 1
  a = arr[i]
  j = i + 1
  while j < len
    b = arr[j]
    doSomething a, b
    j++
  i++

或者可读性差一点:

i = 0; len = arr.length - 1
while i < len
  a = arr[i++]; j = i
  while j <= len
    doSomething a, arr[j++]
于 2017-09-29T23:03:23.670 回答